How to create a numpy array to describe the vertices of a triangle?

若如初见. 提交于 2021-02-08 06:22:23

问题


I like to use Numpy to create an array of vertices that is to be passed into glsl.

Vertices will be a numpy array that comprises the info of 3 vertex.

Each vertex consist of:

  1. pos = (x, y) a 64-bit signed floating-point format that has a 32-bit R component in bytes 0..3, and a 32-bit G component in bytes 4..7, and
  2. color = (r, g, b) a 96-bit signed floating-point format that has a 32-bit R component in bytes 0..3, a 32-bit G component in bytes 4..7, and a 32-bit B component in bytes 8..11

i.e. each vertex = (pos, color) = ( (x, y), (r, g, b) )

A triangle has 3 vertices, so finally I need a 1D numpy array to describe

Vertices = [vertex1, vertex2, vertex3]
         = [ ( (x, y), (r, g, b) ), 
             ( (x, y), (r, g, b) ), 
             ( (x, y), (r, g, b) ) ] 

How can I create Vertices in numpy? The below syntax looks wrong.

Vertices = np.array([( (x1, y1), (r1, g1, b1) ), 
                     ( (x2, y2), (r2, g2, b2) ), 
                     ( (x3, y3), (r3, g3, b3) )], dtype=np.float32)

The bytes size of each vertex should be 64/8 + 96/8 = 8 + 12 = 20 bytes. The bytes size of Vertices should be 20 bytes x 3 = 60 bytes.


回答1:


This is quite simple, in numpy actually. Use structured arrays:

In [21]: PosType = np.dtype([('x','f4'), ('y','f4')])

In [22]: ColorType = np.dtype([('r','f4'), ('g', 'f4'), ('b', 'f4')])

In [23]: VertexType = np.dtype([('pos', PosType),('color', ColorType)])

In [24]: VertexType
Out[24]: dtype([('pos', [('x', '<f4'), ('y', '<f4')]), ('color', [('r', '<f4'), ('g', '<f4'), ('b', '<f4')])])

In [25]: VertexType.itemsize
Out[25]: 20

Then simply:

In [26]: vertices = np.array([( (1, 2), (3, 4, 5) ),
    ...:                      ( (6, 7), (8, 9, 10) ),
    ...:                      ( (11, 12), (13, 14, 15) )], dtype=VertexType)

In [27]: vertices.shape
Out[27]: (3,)

And basic indexing:

In [28]: vertices[0]
Out[28]: (( 1.,  2.), ( 3.,  4.,  5.))

In [29]: vertices[0]['pos']
Out[29]: ( 1.,  2.)

In [30]: vertices[0]['pos']['y']
Out[30]: 2.0

In [31]: VertexType.itemsize
Out[31]: 20

numpy ever provides record-arrays, so you can use attribute-access instead of indexing:

In [32]: vertices = np.rec.array([( (1, 2), (3, 4, 5) ),
    ...:                          ( (6, 7), (8, 9, 10) ),
    ...:                          ( (11, 12), (13, 14, 15) )], dtype=VertexType)

In [33]: vertices[0].pos
Out[33]: (1.0, 2.0)

In [34]: vertices[0].pos.x
Out[34]: 1.0

In [35]: vertices[2].color.g
Out[35]: 14.0


来源:https://stackoverflow.com/questions/51891518/how-to-create-a-numpy-array-to-describe-the-vertices-of-a-triangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!