繁体   English   中英

如何创建一个 numpy 数组来描述三角形的顶点?

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

我喜欢使用 Numpy 创建要传递到glsl的顶点数组。

Vertices将是一个包含 3 个顶点信息的 numpy 数组。

每个vertex包括:

  1. pos = (x, y) 64 位有符号浮点格式,在字节 0..3 中具有 32 位 R 分量,在字节 4..7 中具有 32 位 G 分量,并且
  2. color = (r, g, b) 96 位有符号浮点格式,在字节 0..3 中具有 32 位 R 分量,在字节 4..7 中具有 32 位 G 分量,以及 32-以字节为单位的 B 位分量 8..11

即每个vertex = (pos, color) = ( (x, y), (r, g, b) )

一个三角形有 3 个顶点,所以最后我需要一个 1D numpy 数组来描述

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

如何在 numpy 中创建Vertices 下面的语法看起来不对。

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

每个vertex的字节大小应为 64/8 + 96/8 = 8 + 12 = 20 字节。 Vertices的字节大小应为 20 字节 x 3 = 60 字节。

这很简单,实际上在numpy 使用结构化数组

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

然后简单地:

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,)

和基本索引:

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曾经提供记录数组,因此您可以使用属性访问而不是索引:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM