代码之家  ›  专栏  ›  技术社区  ›  Sun Bear

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

  •  2
  • Sun Bear  · 技术社区  · 8 年前

    我喜欢用numpy创建一个顶点数组 glsl .

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

    vertex 包括:

    1. pos = (x, y) 一种64位有符号浮点格式,具有32位 字节0..3中的r分量,字节4..7中的32位g分量, 和
    2. color = (r, g, b) 一种96位有符号浮点格式,具有 字节0..3中的32位r组件,字节中的32位g组件 4..7,以及字节8..11中的32位B组件

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

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

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

    我如何创建 顶点 麻木了吗? 下面的语法错误。

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

    每个字节的大小 顶点 应该是64/8+96/8=8+12=20字节。 的字节大小 顶点 应该是20字节x 3=60字节。

    1 回复  |  直到 8 年前
        1
  •  2
  •   juanpa.arrivillaga    8 年前

    这很简单,在 numpy 事实上。使用 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
    

    然后简单地说:

    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
    

    麻木的 提供了记录数组,因此可以使用属性访问而不是索引:

    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