关于不编译的第一条:
struct vector2d {
GLfloat x, y;
};
void draw_polygon(struct vector2d* center, int num_points,
struct vector2d* points, int mode)
{ //1st GL_FLOAT is not a type, use GLfloat
int i;
int offset=0;
GLfloat *arr;
if(mode == GL_TRIANGLE_FAN) { //what was that "i" doing here
arr = (GLfloat *)malloc(sizeof(GLfloat) * ((num_points+1)*2)); //no "*" before arr
arr[0]=center->x;
arr[1]=center->y;
offset = 2;
}
else{
arr = (GLfloat *)malloc(sizeof(GLfloat) * (num_points*2)) ; //no "*" before arr; Why do you typcast it to "(int *)"?
}
for(i = 0; i < num_points; i++){
int g = (i*2)+offset;//i*2
arr[g]=points[i].x;
arr[g+1]=points[i].y;
i++;
}
}
至于做整个代码。GLES 不适用于开始/结束调用,但您必须调用绘图调用。此时,使用上面的代码创建一个顶点数据数组,现在您需要将其推送到 GPU(或设置数据的指针)并调用glDrawArrays
.
所以你需要添加:
glEnableClientState(GL_VERTEX_ARRAY); //this is usually set only once unless you want to disable it at some point for some very unlikelly reason
glVertexPointer(2, GL_FLOAT, 0, arr); //set the pointer (alternative is to use the VBO and copy the data directly to the GPU)
glDrawArrays(mode, 0, num_points+offset/2);
free(arr); //you need to free the allocated memory
在同一个函数中。
为了让你的方法看起来不那么复杂,你可以试试这个:
void draw_polygon2(struct vector2d* center, int num_points, struct vector2d* points, int mode) {
if(mode == GL_TRIANGLE_FAN) {
vector2d *newBuffer = (vector2d *)malloc(sizeof(vector2d)*(num_points+1));//create a new buffer just to append center to beginning
newBuffer[0] = *center; //copy center
memcpy(newBuffer+1, points, sizeof(vector2d)*num_points); //copy all other points after center
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, sizeof(vector2d), newBuffer);
glDrawArrays(mode, 0, num_points+1);
free(newBuffer);
}
else {
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, sizeof(vector2d), points);
glDrawArrays(mode, 0, num_points);
}
}
请注意,由于此函数直接使用 vector2d 结构,因此 x 和 y 是 vector2d 结构中的前两个参数。即使您将“z”添加为第三个参数,代码也应该可以工作。