簡體   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