2011-04-20 78 views
1

我想實現功能,以便我可以在運行時向頂點數組添加/移除頂點。 有沒有這樣做的常見方法?OpenGL ES - 更新頂點數組,添加/刪除頂點

頂點數據的推薦格式似乎是C數組的結構, 所以我試了下面。保持一個指向頂點結構數組財產:

@property Vertex *vertices; 

,然後作出一個新的陣列和在

- (void) addVertex:(Vertex)newVertex 
{ 
    int numberOfVertices = sizeof(vertices)/sizeof(Vertex); 
    Vertex newArray[numberOfVertices + 1]; 

    for (int i = 0; i < numberOfVertices; i++) 
     newArray[i] = vertices[i]; 

    newArray[numberOfVertices] = newVertex; 
    self.vertices = newArray; 
} 

,但沒有運氣的數據複製。我不是在C究竟有信心所以很可能這真是小巫見大巫..

回答

1

這是怎麼了我只是做了它:

//verts is an NSMutableArray and I want to have an CGPoint c array to use with 
// glVertexPointer(2, GL_FLOAT, 0, vertices);... so: 

CGPoint vertices[[verts count]]; 
for(int i=0; i<[verts count]; i++) 
{ 
    vertices[i] = [[verts objectAtIndex:i] CGPointValue]; 
} 
0

這裏就是我現在就這樣做:

// re-allocate the array dynamically. 
// realloc() will act like malloc() if vertices == NULL 
Vertex newVertex = {{x,y},{r,g,b,a}}; 
numberOfVertices++; 
vertices = (Vertex *) realloc(vertices, sizeof(Vertex) * numberOfVertices); 
if(vertices == NULL) NSLog(@"FAIL allocating memory for vertex array"); 
else vertices[numberOfVertices - 1] = newVertex; 

// clean up memory once i don't need the array anymore 
if(vertices != NULL) free(vertices); 

我假設icnivad的上面的方法更靈活,因爲你可以用NSMutableArray做更多的事情,但使用帶有malloc/realloc的普通C數組應該(更快?)。