void VSResSurfRevLib::computeVAOSquare(float* p) { GLuint faceIndex[] = { 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23 }; float texCoords[] = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, }; float normals[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, }; glGenVertexArrays(1, &mMyMesh[objId].vao); glBindVertexArray(mMyMesh[objId].vao); mMyMesh[objId].numIndexes = sizeof(faceIndex); GLuint buffers[4]; glGenBuffers(4, buffers); //vertex coordinates buffer glBindBuffer(GL_ARRAY_BUFFER, buffers[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 24 * 4, p, GL_STATIC_DRAW); glEnableVertexAttribArray(VSShaderLib::VERTEX_COORD_ATTRIB); glVertexAttribPointer(VSShaderLib::VERTEX_COORD_ATTRIB, 4, GL_FLOAT, 0, 0, 0); //texture coordinates buffer glBindBuffer(GL_ARRAY_BUFFER, buffers[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords), texCoords, GL_STATIC_DRAW); glEnableVertexAttribArray(VSShaderLib::TEXTURE_COORD_ATTRIB); glVertexAttribPointer(VSShaderLib::TEXTURE_COORD_ATTRIB, 2, GL_FLOAT, 0, 0, 0); //normals buffer glBindBuffer(GL_ARRAY_BUFFER, buffers[2]); glBufferData(GL_ARRAY_BUFFER, sizeof(normals), normals, GL_STATIC_DRAW); glEnableVertexAttribArray(VSShaderLib::NORMAL_ATTRIB); glVertexAttribPointer(VSShaderLib::NORMAL_ATTRIB, 4, GL_FLOAT, GL_FALSE, 0, 0); //index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[3]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, mMyMesh[objId].numIndexes, faceIndex, GL_STATIC_DRAW); //Unbind the VAO glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableVertexAttribArray(VSShaderLib::VERTEX_COORD_ATTRIB); glDisableVertexAttribArray(VSShaderLib::NORMAL_ATTRIB); glDisableVertexAttribArray(VSShaderLib::TEXTURE_COORD_ATTRIB); mMyMesh[objId].type = GL_TRIANGLES; }
void genVAOsAndUniformBuffer(const aiScene *sc) { struct MyMesh aMesh; struct MyMaterial aMat; GLuint buffer; // For each mesh for (unsigned int n = 0; n < sc->mNumMeshes; ++n) { const aiMesh* mesh = sc->mMeshes[n]; // create array with faces // have to convert from Assimp format to array unsigned int *faceArray; faceArray = (unsigned int *)malloc(sizeof(unsigned int) * mesh->mNumFaces * 3); unsigned int faceIndex = 0; for (unsigned int t = 0; t < mesh->mNumFaces; ++t) { const aiFace* face = &mesh->mFaces[t]; memcpy(&faceArray[faceIndex], face->mIndices,3 * sizeof(unsigned int)); faceIndex += 3; } aMesh.numFaces = sc->mMeshes[n]->mNumFaces; // generate Vertex Array for mesh glGenVertexArrays(1,&(aMesh.vao)); glBindVertexArray(aMesh.vao); // buffer for faces glGenBuffers(1, &buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mesh->mNumFaces * 3, faceArray, GL_STATIC_DRAW); // buffer for vertex positions if (mesh->HasPositions()) { glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*mesh->mNumVertices, mesh->mVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(vertexLoc); glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, 0, 0, 0); } // buffer for vertex normals if (mesh->HasNormals()) { glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*mesh->mNumVertices, mesh->mNormals, GL_STATIC_DRAW); glEnableVertexAttribArray(normalLoc); glVertexAttribPointer(normalLoc, 3, GL_FLOAT, 0, 0, 0); } // buffer for vertex texture coordinates if (mesh->HasTextureCoords(0)) { float *texCoords = (float *)malloc(sizeof(float)*2*mesh->mNumVertices); for (unsigned int k = 0; k < mesh->mNumVertices; ++k) { texCoords[k*2] = mesh->mTextureCoords[0][k].x; texCoords[k*2+1] = mesh->mTextureCoords[0][k].y; } glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*mesh->mNumVertices, texCoords, GL_STATIC_DRAW); glEnableVertexAttribArray(texCoordLoc); glVertexAttribPointer(texCoordLoc, 2, GL_FLOAT, 0, 0, 0); } // unbind buffers glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER,0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); // create material uniform buffer aiMaterial *mtl = sc->mMaterials[mesh->mMaterialIndex]; aiString texPath; //contains filename of texture if(AI_SUCCESS == mtl->GetTexture(aiTextureType_DIFFUSE, 0, &texPath)){ //bind texture unsigned int texId = textureIdMap[texPath.data]; aMesh.texIndex = texId; aMat.texCount = 1; } else aMat.texCount = 0; float c[4]; set_float4(c, 0.8f, 0.8f, 0.8f, 1.0f); aiColor4D diffuse; if(AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_DIFFUSE, &diffuse)) color4_to_float4(&diffuse, c); memcpy(aMat.diffuse, c, sizeof(c)); set_float4(c, 0.2f, 0.2f, 0.2f, 1.0f); aiColor4D ambient; if(AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_AMBIENT, &ambient)) color4_to_float4(&ambient, c); memcpy(aMat.ambient, c, sizeof(c)); set_float4(c, 0.0f, 0.0f, 0.0f, 1.0f); aiColor4D specular; if(AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_SPECULAR, &specular)) color4_to_float4(&specular, c); memcpy(aMat.specular, c, sizeof(c)); set_float4(c, 0.0f, 0.0f, 0.0f, 1.0f); aiColor4D emission; if(AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_EMISSIVE, &emission)) color4_to_float4(&emission, c); memcpy(aMat.emissive, c, sizeof(c)); float shininess = 0.0; unsigned int max; aiGetMaterialFloatArray(mtl, AI_MATKEY_SHININESS, &shininess, &max); aMat.shininess = shininess; glGenBuffers(1,&(aMesh.uniformBlockIndex)); glBindBuffer(GL_UNIFORM_BUFFER,aMesh.uniformBlockIndex); glBufferData(GL_UNIFORM_BUFFER, sizeof(aMat), (void *)(&aMat), GL_STATIC_DRAW); myMeshes.push_back(aMesh); } }
void display_handler(void) { // clear scene glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor3f(1,1,1); shader.Bind(); // pass uniform variables to shader GLint projectionMatrix_location = glGetUniformLocation(shader.ID(), "projectionMatrix"); GLint viewMatrix_location = glGetUniformLocation(shader.ID(), "viewMatrix"); GLint modelMatrix_location = glGetUniformLocation(shader.ID(), "modelMatrix"); GLint normalMatrix_location = glGetUniformLocation(shader.ID(), "normalMatrix"); GLint materialAmbient_location = glGetUniformLocation(shader.ID(), "materialAmbient"); GLint materialDiffuse_location = glGetUniformLocation(shader.ID(), "materialDiffuse"); GLint materialSpecular_location = glGetUniformLocation(shader.ID(), "materialSpecular"); GLint lightPosition_location = glGetUniformLocation(shader.ID(), "lightPosition"); GLint lightAmbient_location = glGetUniformLocation(shader.ID(), "lightAmbient"); GLint lightDiffuse_location = glGetUniformLocation(shader.ID(), "lightDiffuse"); GLint lightSpecular_location = glGetUniformLocation(shader.ID(), "lightSpecular"); GLint lightGlobal_location = glGetUniformLocation(shader.ID(), "lightGlobal"); GLint materialShininess_location = glGetUniformLocation(shader.ID(), "materialShininess"); GLint constantAttenuation_location = glGetUniformLocation(shader.ID(), "constantAttenuation"); GLint linearAttenuation_location = glGetUniformLocation(shader.ID(), "linearAttenuation"); GLint useTexture_location = glGetUniformLocation(shader.ID(), "useTexture"); glUniformMatrix4fv( projectionMatrix_location, 1, GL_FALSE, &projectionMatrix[0][0]); glUniformMatrix4fv( viewMatrix_location, 1, GL_FALSE, &viewMatrix[0][0]); glUniformMatrix4fv( modelMatrix_location, 1, GL_FALSE, &modelMatrix[0][0]); glUniformMatrix3fv( normalMatrix_location, 1, GL_FALSE, &normalMatrix[0][0]); glUniform3fv( materialAmbient_location, 1, materialAmbient); glUniform3fv( materialDiffuse_location, 1, materialDiffuse); glUniform3fv( materialSpecular_location, 1, materialSpecular); glUniform3fv( lightPosition_location, 1, lightPosition); glUniform3fv( lightAmbient_location, 1, lightAmbient); glUniform3fv( lightDiffuse_location, 1, lightDiffuse); glUniform3fv( lightSpecular_location, 1, lightSpecular); glUniform3fv( lightGlobal_location, 1, lightGlobal); glUniform1f( materialShininess_location, materialShininess); glUniform1f( constantAttenuation_location, constantAttenuation); glUniform1f( linearAttenuation_location, linearAttenuation); glUniform1i( useTexture_location, useTexture); // bind texture to shader GLint texture0_location = glGetAttribLocation(shader.ID(), "texture0"); if (texture0_location != -1) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textureID); glUniform1i(texture0_location, 0); } // bind vertex uv coordinates to shader GLint uv_location = glGetAttribLocation(shader.ID(), "vertex_uv"); if (uv_location != -1) { glEnableVertexAttribArray(uv_location); glBindBuffer(GL_ARRAY_BUFFER, vertex_uv_buffer); glVertexAttribPointer(uv_location, 2, GL_FLOAT, GL_FALSE, 0, 0); } // bind vertex positions to shader GLint position_location = glGetAttribLocation(shader.ID(), "vertex_position"); if (position_location != -1) { glEnableVertexAttribArray(position_location); glBindBuffer(GL_ARRAY_BUFFER, vertex_position_buffer); glVertexAttribPointer(position_location, 3, GL_FLOAT, GL_FALSE, 0, 0); } // bind vertex normals to shader GLint normal_location = glGetAttribLocation(shader.ID(), "vertex_normal"); if (normal_location != -1) { glEnableVertexAttribArray(normal_location); glBindBuffer(GL_ARRAY_BUFFER, vertex_normal_buffer); glVertexAttribPointer(normal_location, 3, GL_FLOAT, GL_FALSE, 0, 0); } // draw the scene glDrawArrays(GL_TRIANGLES, 0, trig.VertexCount()); glDisableVertexAttribArray(position_location); glDisableVertexAttribArray(uv_location); glDisableVertexAttribArray(normal_location); shader.Unbind(); glFlush(); }
static GLboolean do_test(const struct test_desc *test) { GLuint vs; GLuint progs[2] = { 0 }; GLuint pipes[2]; GLuint bufs[NUM_BUFFERS]; float initial_xfb_buffer_contents[XFB_BUFFER_SIZE]; GLboolean pass = GL_TRUE; int i; int num_varyings = test->mode == NO_VARYINGS ? 0 : test->num_buffers; GLint max_separate_attribs; char* vstext_sep; if (test->mode == USEPROGSTAGE_ACTIVE || test->mode == USEPROGSTAGE_NOACTIVE || test->mode == BIND_PIPELINE) { piglit_require_extension("GL_ARB_separate_shader_objects"); if (piglit_get_gl_version() >= 32) asprintf(&vstext_sep, vstext_sep_template, 150); else asprintf(&vstext_sep, vstext_sep_template, 110); } glGetIntegerv(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, &max_separate_attribs); printf("MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTIBS=%i\n", max_separate_attribs); printf("Compile vertex shader\n"); vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vstext); if (test->mode == USEPROGSTAGE_ACTIVE || test->mode == USEPROGSTAGE_NOACTIVE || test->mode == BIND_PIPELINE) { /* Note, we can't use glCreateShaderProgramv because the setup * of transform feedback must be done before linking */ vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vstext_sep); progs[0] = glCreateProgram(); glProgramParameteri(progs[0], GL_PROGRAM_SEPARABLE, GL_TRUE); glAttachShader(progs[0], vs); } else if (test->mode == NOT_A_PROGRAM) { printf("Create a program and then delete it\n"); progs[0] = glCreateProgram(); glDeleteProgram(progs[0]); } else { progs[0] = glCreateProgram(); glAttachShader(progs[0], vs); } pass = piglit_check_gl_error(GL_NO_ERROR) && pass; printf("Setup transform feedback for %i varyings in %s mode\n", num_varyings, test->buffer_mode == GL_INTERLEAVED_ATTRIBS ? "interleaved" : "separate"); glTransformFeedbackVaryings(progs[0], num_varyings, varyings, test->buffer_mode); if (test->mode == NOT_A_PROGRAM) { pass = piglit_check_gl_error(GL_INVALID_VALUE) && pass; return pass; } printf("Link program\n"); glLinkProgram(progs[0]); pass = piglit_link_check_status(progs[0]) && pass; if (test->mode == USEPROGSTAGE_ACTIVE || test->mode == USEPROGSTAGE_NOACTIVE || test->mode == BIND_PIPELINE) { printf("Create 2nd program for the pipeline\n"); progs[1] = glCreateShaderProgramv(GL_VERTEX_SHADER, 1, (const char **) &vstext_sep); pass = piglit_link_check_status(progs[1]) && pass; } if (test->mode == USEPROG_ACTIVE || test->mode == LINK_OTHER_ACTIVE) { printf("Prepare 2nd program\n"); progs[1] = glCreateProgram(); glAttachShader(progs[1], vs); } if (test->mode == USEPROG_ACTIVE) { printf("Link 2nd program\n"); glLinkProgram(progs[1]); pass = piglit_link_check_status(progs[1]) && pass; } if (test->mode == USEPROGSTAGE_ACTIVE || test->mode == USEPROGSTAGE_NOACTIVE || test->mode == BIND_PIPELINE) { printf("Use pipeline\n"); glGenProgramPipelines(2, pipes); glUseProgramStages(pipes[0], GL_VERTEX_SHADER_BIT, progs[0]); glUseProgramStages(pipes[1], GL_VERTEX_SHADER_BIT, progs[1]); glBindProgramPipeline(pipes[0]); } else if (test->mode == SKIP_USE_PROGRAM) { printf("Don't use program\n"); } else { printf("Use program\n"); glUseProgram(progs[0]); } printf("Prepare %i buffers\n", test->num_buffers); glGenBuffers(test->num_buffers, bufs); memset(initial_xfb_buffer_contents, 0, sizeof(initial_xfb_buffer_contents)); for (i = 0; i < test->num_buffers; ++i) { glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, bufs[i]); glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, sizeof(initial_xfb_buffer_contents), initial_xfb_buffer_contents, GL_STREAM_READ); } switch (test->mode) { case BIND_MAX: do_bind(test, bufs[0], max_separate_attribs); pass = piglit_check_gl_error(GL_INVALID_VALUE) && pass; return pass; case BIND_BAD_SIZE: case BIND_BAD_OFFSET: do_bind(test, bufs[0], 0); pass = piglit_check_gl_error(GL_INVALID_VALUE) && pass; return pass; default: break; } for (i = 0; i < test->num_buffers; ++i) { if (test->mode == UNBOUND_BUFFER && i == test->param) { printf("Don't bind buffer %i\n", i); } else { do_bind(test, bufs[i], i); } } pass = piglit_check_gl_error(GL_NO_ERROR) && pass; if (test->mode == END_INACTIVE) { printf("EndTransformFeedback\n"); glEndTransformFeedback(); pass = piglit_check_gl_error(GL_INVALID_OPERATION) && pass; return pass; } printf("BeginTransformFeedback\n"); glBeginTransformFeedback(GL_POINTS); switch (test->mode) { case UNBOUND_BUFFER: case NO_VARYINGS: case SKIP_USE_PROGRAM: pass = piglit_check_gl_error(GL_INVALID_OPERATION) && pass; break; default: pass = piglit_check_gl_error(GL_NO_ERROR) && pass; break; } switch (test->mode) { case BEGIN_ACTIVE: printf("BeginTransformFeedback\n"); glBeginTransformFeedback(GL_POINTS); pass = piglit_check_gl_error(GL_INVALID_OPERATION) && pass; break; case USEPROG_ACTIVE: printf("Use new program\n"); glUseProgram(progs[1]); pass = piglit_check_gl_error(GL_INVALID_OPERATION) && pass; break; case LINK_CURRENT_ACTIVE: printf("Link current program\n"); glLinkProgram(progs[0]); pass = piglit_check_gl_error(GL_INVALID_OPERATION) && pass; break; case LINK_OTHER_ACTIVE: printf("Link 2nd program\n"); glLinkProgram(progs[1]); pass = piglit_check_gl_error(GL_NO_ERROR) && pass; break; case BIND_ACTIVE: do_bind(test, bufs[0], 0); pass = piglit_check_gl_error(GL_INVALID_OPERATION) && pass; break; case USEPROGSTAGE_ACTIVE: printf("Use new program stage\n"); glUseProgramStages(pipes[0], GL_VERTEX_SHADER_BIT, progs[1]); pass = piglit_check_gl_error(GL_INVALID_OPERATION) && pass; break; case USEPROGSTAGE_NOACTIVE: printf("Use new program stage\n"); glUseProgramStages(pipes[1], GL_VERTEX_SHADER_BIT, progs[1]); pass = piglit_check_gl_error(GL_NO_ERROR) && pass; break; case BIND_PIPELINE: printf("Bind a new pipeline\n"); glBindProgramPipeline(pipes[1]); pass = piglit_check_gl_error(GL_INVALID_OPERATION) && pass; break; default: break; } return pass; }
int main() { GLFWwindow * window = initWindow(windowWidth, windowHeight); if (!window) { glfwTerminate(); return -1; } glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, cursor_callback); glfwSetScrollCallback(window, scroll_callback); glEnable(GL_DEPTH_TEST); // prepare an array of vertices GLfloat vertices[] = { // Positions // normal vectors -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f }; glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; GLuint lightVAO; glGenVertexArrays(1, &lightVAO); glBindVertexArray(lightVAO); GLuint lightVBO; glGenBuffers(1, &lightVBO); glBindBuffer(GL_ARRAY_BUFFER, lightVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); Shader shaders("shader.vert", "shader.frag"); Shader lightShaders("lightShader.vert", "lightShader.frag"); double last_frame = glfwGetTime(); while (!glfwWindowShouldClose(window)) { double current_frame = glfwGetTime(); double delta_time = current_frame - last_frame; last_frame = current_frame; glfwPollEvents(); do_movement(delta_time); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GLfloat light_pos_angle = glm::radians(60.0f * current_frame); glm::vec3 light_pos(1.2f + sin(light_pos_angle), 1.0f, 2.0f + cos(light_pos_angle)); // draw common container shaders.Use(); glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (GLfloat)windowWidth / (GLfloat)windowHeight, 0.01f, 1000.0f); shaders.SetUniform("view", view); shaders.SetUniform("projection", projection); shaders.SetUniform("objectColor", glm::vec3(1.0f, 0.5f, 0.31f)); shaders.SetUniform("lightColor", glm::vec3(1.0f, 1.0f, 1.0f)); shaders.SetUniform("lightPos", light_pos); glm::mat4 model = glm::translate(glm::mat4(), cubePositions[0]); model = glm::rotate(model, (GLfloat)glm::radians(60.0f * current_frame), glm::vec3(1.0f, 1.0f, 1.0f)); glm::mat3 normalMatrix = glm::mat3(view *glm::transpose(glm::inverse(model))); shaders.SetUniform("model", model); shaders.SetUniform("normalMatrix", normalMatrix); glBindVertexArray(lightVAO); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); // draw lamp lightShaders.Use(); model = glm::scale(glm::translate(glm::mat4(), light_pos), glm::vec3(0.2f)); lightShaders.SetUniform("view", view); lightShaders.SetUniform("projection", projection); lightShaders.SetUniform("model", model); glBindVertexArray(lightVAO); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glfwSwapBuffers(window); } glfwTerminate(); return 0; }
void ApplicationOverlay::TexturedHemisphere::buildVBO(const float fov, const float aspectRatio, const int slices, const int stacks) { if (fov >= PI) { qDebug() << "TexturedHemisphere::buildVBO(): FOV greater or equal than Pi will create issues"; } // Cleanup old VBO if necessary cleanupVBO(); //UV mapping source: http://www.mvps.org/directx/articles/spheremap.htm // Compute number of vertices needed _vertices = slices * stacks; // Compute vertices positions and texture UV coordinate TextureVertex* vertexData = new TextureVertex[_vertices]; TextureVertex* vertexPtr = &vertexData[0]; for (int i = 0; i < stacks; i++) { float stacksRatio = (float)i / (float)(stacks - 1); // First stack is 0.0f, last stack is 1.0f // abs(theta) <= fov / 2.0f float pitch = -fov * (stacksRatio - 0.5f); for (int j = 0; j < slices; j++) { float slicesRatio = (float)j / (float)(slices - 1); // First slice is 0.0f, last slice is 1.0f // abs(phi) <= fov * aspectRatio / 2.0f float yaw = -fov * aspectRatio * (slicesRatio - 0.5f); vertexPtr->position = getPoint(yaw, pitch); vertexPtr->uv.x = slicesRatio; vertexPtr->uv.y = stacksRatio; vertexPtr++; } } // Create and write to buffer glGenBuffers(1, &_vbo.first); glBindBuffer(GL_ARRAY_BUFFER, _vbo.first); static const int BYTES_PER_VERTEX = sizeof(TextureVertex); glBufferData(GL_ARRAY_BUFFER, _vertices * BYTES_PER_VERTEX, vertexData, GL_STATIC_DRAW); delete[] vertexData; // Compute number of indices needed static const int VERTEX_PER_TRANGLE = 3; static const int TRIANGLE_PER_RECTANGLE = 2; int numberOfRectangles = (slices - 1) * (stacks - 1); _indices = numberOfRectangles * TRIANGLE_PER_RECTANGLE * VERTEX_PER_TRANGLE; // Compute indices order GLushort* indexData = new GLushort[_indices]; GLushort* indexPtr = indexData; for (int i = 0; i < stacks - 1; i++) { for (int j = 0; j < slices - 1; j++) { GLushort bottomLeftIndex = i * slices + j; GLushort bottomRightIndex = bottomLeftIndex + 1; GLushort topLeftIndex = bottomLeftIndex + slices; GLushort topRightIndex = topLeftIndex + 1; *(indexPtr++) = topLeftIndex; *(indexPtr++) = bottomLeftIndex; *(indexPtr++) = topRightIndex; *(indexPtr++) = topRightIndex; *(indexPtr++) = bottomLeftIndex; *(indexPtr++) = bottomRightIndex; } } // Create and write to buffer glGenBuffers(1, &_vbo.second); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbo.second); static const int BYTES_PER_INDEX = sizeof(GLushort); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indices * BYTES_PER_INDEX, indexData, GL_STATIC_DRAW); delete[] indexData; }
GLUSboolean init(GLUSvoid) { // This is a white light. struct LightProperties light = { { 1.0f, 1.0f, 1.0f }, { 0.3f, 0.3f, 0.3f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f } }; // Blue color material with white specular color. struct MaterialProperties material = { { 0.0f, 1.0f, 0.0f, 1.0f }, { 0.0f, 1.0f, 0.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, 20.0f }; GLUStextfile vertexSource; GLUStextfile fragmentSource; GLUSshape wavefrontObj; glusFileLoadText("../Example16/shader/phong.vert.glsl", &vertexSource); glusFileLoadText("../Example16/shader/phong.frag.glsl", &fragmentSource); glusProgramBuildFromSource(&g_program, (const GLUSchar**) &vertexSource.text, 0, 0, 0, (const GLUSchar**) &fragmentSource.text); glusFileDestroyText(&vertexSource); glusFileDestroyText(&fragmentSource); // g_projectionMatrixLocation = glGetUniformLocation(g_program.program, "u_projectionMatrix"); g_modelViewMatrixLocation = glGetUniformLocation(g_program.program, "u_modelViewMatrix"); g_normalMatrixLocation = glGetUniformLocation(g_program.program, "u_normalMatrix"); g_light.directionLocation = glGetUniformLocation(g_program.program, "u_light.direction"); g_light.ambientColorLocation = glGetUniformLocation(g_program.program, "u_light.ambientColor"); g_light.diffuseColorLocation = glGetUniformLocation(g_program.program, "u_light.diffuseColor"); g_light.specularColorLocation = glGetUniformLocation(g_program.program, "u_light.specularColor"); g_material.ambientColorLocation = glGetUniformLocation(g_program.program, "u_material.ambientColor"); g_material.diffuseColorLocation = glGetUniformLocation(g_program.program, "u_material.diffuseColor"); g_material.specularColorLocation = glGetUniformLocation(g_program.program, "u_material.specularColor"); g_material.specularExponentLocation = glGetUniformLocation(g_program.program, "u_material.specularExponent"); g_vertexLocation = glGetAttribLocation(g_program.program, "a_vertex"); g_normalLocation = glGetAttribLocation(g_program.program, "a_normal"); // // Use a helper function to load an wavefront object file. glusShapeLoadWavefront("monkey.obj", &wavefrontObj); g_numberVertices = wavefrontObj.numberVertices; glGenBuffers(1, &g_verticesVBO); glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO); glBufferData(GL_ARRAY_BUFFER, wavefrontObj.numberVertices * 4 * sizeof(GLfloat), (GLfloat*) wavefrontObj.vertices, GL_STATIC_DRAW); glGenBuffers(1, &g_normalsVBO); glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO); glBufferData(GL_ARRAY_BUFFER, wavefrontObj.numberVertices * 3 * sizeof(GLfloat), (GLfloat*) wavefrontObj.normals, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glusShapeDestroyf(&wavefrontObj); // glUseProgram(g_program.program); glGenVertexArrays(1, &g_vao); glBindVertexArray(g_vao); glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO); glVertexAttribPointer(g_vertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_vertexLocation); glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO); glVertexAttribPointer(g_normalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_normalLocation); // glusMatrix4x4LookAtf(g_viewMatrix, 0.0f, 0.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); // glusVector3Normalizef(light.direction); // Transform light to camera space, as it is currently in world space. glusMatrix4x4MultiplyVector3f(light.direction, g_viewMatrix, light.direction); // Set up light ... glUniform3fv(g_light.directionLocation, 1, light.direction); glUniform4fv(g_light.ambientColorLocation, 1, light.ambientColor); glUniform4fv(g_light.diffuseColorLocation, 1, light.diffuseColor); glUniform4fv(g_light.specularColorLocation, 1, light.specularColor); // ... and material values. glUniform4fv(g_material.ambientColorLocation, 1, material.ambientColor); glUniform4fv(g_material.diffuseColorLocation, 1, material.diffuseColor); glUniform4fv(g_material.specularColorLocation, 1, material.specularColor); glUniform1f(g_material.specularExponentLocation, material.specularExponent); // glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); return GLUS_TRUE; }
void Effects::unbind() { shader.end(); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArrayAPPLE(0); }
void Effects::setup(int w, int h) { width = w; height = h; cracks.setup(w,h); // create fbo glGenFramebuffers(1, &fbo_handle); eglGetError(); glBindFramebuffer(GL_FRAMEBUFFER, fbo_handle); // create texture. glGenTextures(1, &fbo_tex); eglGetError(); glActiveTexture(GL_TEXTURE0); eglGetError(); glBindTexture(GL_TEXTURE_2D, fbo_tex); eglGetError(); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); eglGetError(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); eglGetError(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); eglGetError(); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo_tex, 0); eglGetError(); glGenRenderbuffers(1, &fbo_depth); eglGetError(); // render buffer glBindRenderbuffer(GL_RENDERBUFFER, fbo_depth); eglGetError(); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w, h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo_depth); eglGetError(); GLenum drawbufs[] = {GL_COLOR_ATTACHMENT0}; glDrawBuffers(1, drawbufs); glBindFramebuffer(GL_FRAMEBUFFER, 0); if(!shader.load("effects/effects")) { printf("Error loading effects shader.\n"); } vertices[0].setPos(-1, -1, 0); vertices[1].setPos(1, -1, 0); vertices[2].setPos(1, 1, 0); vertices[3].setPos(-1, 1, 0); float mw = 1; float mh = 1; vertices[0].setTex(0, 0); vertices[1].setTex(mw, 0); vertices[2].setTex(mw, mh); vertices[3].setTex(0, mh); glGenVertexArraysAPPLE(1, &vao); eglGetError(); glBindVertexArrayAPPLE(vao); eglGetError(); GLint pos_attrib = glGetAttribLocation(shader.getProgram(), "pos"); GLint tex_attrib = glGetAttribLocation(shader.getProgram(), "tex"); glEnableVertexAttribArray(pos_attrib); glEnableVertexAttribArray(tex_attrib); glGenBuffers(1, &vbo); eglGetError(); glBindBuffer(GL_ARRAY_BUFFER, vbo); eglGetError(); glBufferData( GL_ARRAY_BUFFER ,sizeof(Vertex) * 4 ,vertices[0].pos ,GL_STATIC_DRAW ); eglGetError(); glVertexAttribPointer( pos_attrib ,3 ,GL_FLOAT ,GL_FALSE ,sizeof(Vertex) ,offsetof(Vertex, pos) ); glVertexAttribPointer( tex_attrib ,2 ,GL_FLOAT ,GL_FALSE ,sizeof(Vertex) ,(GLvoid*)offsetof(Vertex, tex) ); calcCenter(); unbind(); flip(false); mirror(false); crack(false); }
Skybox::Skybox() { GLfloat vertex_array_data[] = { -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, -10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, -10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, 10.0f, -10.0f, 10.0f, 10.0f, -10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f, -10.0f, 10.0f, 10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, -10.0f, 10.0f, -10.0f, -10.0f, -10.0f, -10.0f, 10.0f, 10.0f, -10.0f, 10.0f }; nverts = 36; // Generate one vertex array object (VAO) and bind it glGenVertexArrays(1, &(vao)); glBindVertexArray(vao); // Generate two buffer IDs glGenBuffers(1, &vertexbuffer); // Activate the vertex buffer glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); // Present our vertex coordinates to OpenGL glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_array_data), &vertex_array_data, GL_STATIC_DRAW); // Specify how many attribute arrays we have in our VAO glEnableVertexAttribArray(0); // Vertex coordinates glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (void*)0); // xyz coordinates // Deactivate (unbind) the VAO and the buffers again. glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); }
//-------------------------------------------------------------- void ofVbo::bind(){ if(supportVAOs){ if(vaoID==0){ glGenVertexArrays(1, &vaoID); if(vaoID!=0){ retainVAO(vaoID); }else{ supportVAOs = false; ofLogVerbose("ofVbo") << "bind(): error allocating VAO, disabling VAO support"; } } glBindVertexArray(vaoID); } if(vaoChanged || !supportVAOs){ bool programmable = ofIsGLProgrammableRenderer(); if(bUsingVerts){ glBindBuffer(GL_ARRAY_BUFFER, vertId); if(!programmable){ #ifndef TARGET_PROGRAMMABLE_GL glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(vertSize, GL_FLOAT, vertStride, 0); #endif }else{ glEnableVertexAttribArray(ofShader::POSITION_ATTRIBUTE); glVertexAttribPointer(ofShader::POSITION_ATTRIBUTE, vertSize, GL_FLOAT, GL_FALSE, vertStride, 0); } }else if(supportVAOs){ if(!programmable){ #ifndef TARGET_PROGRAMMABLE_GL glDisableClientState(GL_VERTEX_ARRAY); #endif }else{ glDisableVertexAttribArray(ofShader::POSITION_ATTRIBUTE); } } if(bUsingColors) { glBindBuffer(GL_ARRAY_BUFFER, colorId); if(!programmable){ #ifndef TARGET_PROGRAMMABLE_GL glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_FLOAT, colorStride, 0); #endif }else{ glEnableVertexAttribArray(ofShader::COLOR_ATTRIBUTE); glVertexAttribPointer(ofShader::COLOR_ATTRIBUTE, 4, GL_FLOAT, GL_FALSE, colorStride, 0); } }else if(supportVAOs){ if(!programmable){ #ifndef TARGET_PROGRAMMABLE_GL glDisableClientState(GL_COLOR_ARRAY); #endif }else{ glDisableVertexAttribArray(ofShader::COLOR_ATTRIBUTE); } } if(bUsingNormals) { glBindBuffer(GL_ARRAY_BUFFER, normalId); if(!programmable){ #ifndef TARGET_PROGRAMMABLE_GL glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, normalStride, 0); #endif }else{ // tig: note that we set the 'Normalize' flag to true here, assuming that mesh normals need to be // normalized while being uploaded to GPU memory. // http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribPointer.xml // Normalizing the normals on the shader is probably faster, but sending non-normalized normals is // more prone to lead to artifacts difficult to diagnose, especially with the built-in 3D primitives. // If you need to optimise this, and you've dug this far through the code, you are most probably // able to roll your own client code for binding & rendering vbos anyway... glEnableVertexAttribArray(ofShader::NORMAL_ATTRIBUTE); glVertexAttribPointer(ofShader::NORMAL_ATTRIBUTE, 3, GL_FLOAT, GL_TRUE, normalStride, 0); } }else if(supportVAOs){ if(!programmable){ #ifndef TARGET_PROGRAMMABLE_GL glDisableClientState(GL_NORMAL_ARRAY); #endif }else{ glDisableVertexAttribArray(ofShader::NORMAL_ATTRIBUTE); } } if(bUsingTexCoords) { glBindBuffer(GL_ARRAY_BUFFER, texCoordId); if(!programmable){ #ifndef TARGET_PROGRAMMABLE_GL glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, texCoordStride, 0); #endif }else{ glEnableVertexAttribArray(ofShader::TEXCOORD_ATTRIBUTE); glVertexAttribPointer(ofShader::TEXCOORD_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, texCoordStride, 0); } }else if(supportVAOs){ if(!programmable){ #ifndef TARGET_PROGRAMMABLE_GL glDisableClientState(GL_TEXTURE_COORD_ARRAY); #endif }else{ glDisableVertexAttribArray(ofShader::TEXCOORD_ATTRIBUTE); } } if (bUsingIndices) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexId); } map<int,GLuint>::iterator it; for(it=attributeIds.begin();it!=attributeIds.end();it++){ glBindBuffer(GL_ARRAY_BUFFER, attributeIds[it->first]); glEnableVertexAttribArray(it->first); glVertexAttribPointer(it->first, attributeNumCoords[it->first], GL_FLOAT, GL_FALSE, attributeStrides[it->first], 0); if(ofIsGLProgrammableRenderer()){ bUsingVerts |= it->first == ofShader::POSITION_ATTRIBUTE; bUsingColors |= it->first == ofShader::COLOR_ATTRIBUTE; bUsingTexCoords |= it->first == ofShader::TEXCOORD_ATTRIBUTE; bUsingNormals |= it->first == ofShader::NORMAL_ATTRIBUTE; } } vaoChanged=false; } shared_ptr<ofGLProgrammableRenderer> renderer = ofGetGLProgrammableRenderer(); if(renderer){ renderer->setAttributes(bUsingVerts,bUsingColors,bUsingTexCoords,bUsingNormals); } bBound = true; }
int GLSL::enter() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "Advanced GLSL LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glewExperimental = GL_TRUE; glewInit(); glViewport(0, 0, screenWidth, screenHeight); glEnable(GL_DEPTH_TEST); glEnable(GL_PROGRAM_POINT_SIZE); Shader shaderRed("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboRed.frag"); Shader shaderGreen("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboGreen.frag"); Shader shaderBlue("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboBlue.frag"); Shader shaderYellow("../_ShaderSource/advanced/ubo.vs", "../_ShaderSource/advanced/uboYellow.frag"); #pragma region "object_initialization" GLfloat cubeVertices[] = { -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f }; // Setup cube VAO GLuint cubeVAO, cubeVBO; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &cubeVBO); glBindVertexArray(cubeVAO); glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glBindVertexArray(0); #pragma endregion // create a uniform buffer object // first we get the relevant block indices GLuint uniformBlockIndexRed = glGetUniformBlockIndex(shaderRed.Program, "Matrices"); GLuint uniformBlockIndexGreen = glGetUniformBlockIndex(shaderGreen.Program, "Matrices"); GLuint uniformBlockIndexBlue = glGetUniformBlockIndex(shaderBlue.Program, "Matrices"); GLuint uniformBlockIndexYellow = glGetUniformBlockIndex(shaderYellow.Program, "Matrices"); // then we link each shader's uniform block to this uniform binding point glUniformBlockBinding(shaderRed.Program, uniformBlockIndexRed, 0); glUniformBlockBinding(shaderGreen.Program, uniformBlockIndexGreen, 0); glUniformBlockBinding(shaderBlue.Program, uniformBlockIndexBlue, 0); glUniformBlockBinding(shaderYellow.Program, uniformBlockIndexYellow, 0); // now actually create the buffer GLuint uboMatrices; glGenBuffers(1, &uboMatrices); glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices); glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(glm::mat4), NULL, GL_STATIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); // define the range of the buffer that links to a uniform binding point... glBindBufferRange(GL_UNIFORM_BUFFER, 0, uboMatrices, 0, 2 * sizeof(glm::mat4)); // store the projection matrix glm::mat4 projection = glm::perspective(45.0f, (float)screenWidth / (float)screenHeight, 0.1f, 100.0f); glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4), glm::value_ptr(projection)); glBindBuffer(GL_UNIFORM_BUFFER, 0); //glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); // game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_Movement(); // Clear buffers glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ////////////////////////////////////////////////////////////////////////// // set the view and projection matrix in the uniform block glm::mat4 view = camera.GetViewMatrix(); glBindBuffer(GL_UNIFORM_BUFFER, uboMatrices); glBufferSubData(GL_UNIFORM_BUFFER, sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(view)); glBindBuffer(GL_UNIFORM_BUFFER, 0); // draw 4 cubes //RED glBindVertexArray(cubeVAO); shaderRed.Use(); glm::mat4 model; model = glm::translate(model, glm::vec3(-0.75f, 0.75f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(shaderRed.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); ////GREEN //shaderGreen.Use(); //model = glm::mat4(); //model = glm::translate(model, glm::vec3(0.75f, 0.75f, 0.0f)); //glUniformMatrix4fv(glGetUniformLocation(shaderGreen.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); //glDrawArrays(GL_TRIANGLES, 0, 36); ////BLUE //shaderBlue.Use(); //model = glm::mat4(); //model = glm::translate(model, glm::vec3(-0.75f, -0.75f, 0.0f)); //glUniformMatrix4fv(glGetUniformLocation(shaderBlue.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); //glDrawArrays(GL_TRIANGLES, 0, 36); //// //shaderYellow.Use(); //model = glm::mat4(); //model = glm::translate(model, glm::vec3(0.75f, -0.75f, 0.0f)); //glUniformMatrix4fv(glGetUniformLocation(shaderYellow.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); //glDrawArrays(GL_TRIANGLES, 0, 36); // glfwSwapBuffers(window); } glfwTerminate(); return 0; }
void CGLvbo::Bind() const { glBindVertexArray(mVAO); checkGLError(); GLuint attributeIndex = 0; if(mVertObjId < UINT_MAX) { // 1rst attribute buffer : vertices glEnableVertexAttribArray(attributeIndex); checkGLError(); glBindBuffer(GL_ARRAY_BUFFER, mVertObjId); checkGLError(); glVertexAttribPointer( attributeIndex, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride nullptr // array buffer offset ); checkGLError(); ++attributeIndex; } if(mNormObjId < UINT_MAX) { // 2nd attribute buffer : normals glEnableVertexAttribArray(attributeIndex); checkGLError(); glBindBuffer(GL_ARRAY_BUFFER, mNormObjId); checkGLError(); glVertexAttribPointer( attributeIndex, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride nullptr // array buffer offset ); checkGLError(); ++attributeIndex; } if(mUVObjId < UINT_MAX) { // 3rd attribute buffer : UVs glEnableVertexAttribArray(attributeIndex); checkGLError(); glBindBuffer(GL_ARRAY_BUFFER, mUVObjId); checkGLError(); glVertexAttribPointer( attributeIndex, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride nullptr // array buffer offset ); checkGLError(); ++attributeIndex; } }
void VSResSurfRevLib::computeVAO(int numP, float *p, float *points, int sides, float smoothCos) { // Compute and store vertices int numSides = sides; int numPoints = numP + 2; float *vertex = (float *)malloc(sizeof(float)*numP * 2 * 4 * (numSides+1)); float *normal = (float *)malloc(sizeof(float)*numP * 2 * 4 * (numSides+1)); float *textco = (float *)malloc(sizeof(float)*numP * 2 * 4 * (numSides+1)); float inc = 2 * 3.14159f / (numSides); float nx,ny; float delta; int smooth; std::vector<int> smoothness; int k = 0; for(int i=0; i < numP; i++) { revSmoothNormal2(points+(i*2),&nx,&ny, smoothCos, 0); for(int j=0; j<=numSides;j++) { if ((i == 0 && p[0] == 0.0f) || ( i == numP-1 && p[(i+1)*2] == 0.0)) delta = inc * 0.5f; else delta = 0.0f; normal[((k)*(numSides+1) + j)*4] = nx * cos(j*inc+delta); normal[((k)*(numSides+1) + j)*4+1] = ny; normal[((k)*(numSides+1) + j)*4+2] = nx * sin(-j*inc+delta); normal[((k)*(numSides+1) + j)*4+3] = 0.0f; vertex[((k)*(numSides+1) + j)*4] = p[i*2] * cos(j*inc); vertex[((k)*(numSides+1) + j)*4+1] = p[(i*2)+1]; vertex[((k)*(numSides+1) + j)*4+2] = p[i*2] * sin(-j*inc); vertex[((k)*(numSides+1) + j)*4+3] = 1.0f; textco[((k)*(numSides+1) + j)*4] = ((j+0.0f)/numSides); textco[((k)*(numSides+1) + j)*4+1] = (i+0.0f)/(numP-1); textco[((k)*(numSides+1) + j)*4+2] = 0; textco[((k)*(numSides+1) + j)*4+3] = 1.0f; } k++; if (i < numP-1) { smooth = revSmoothNormal2(points+((i+1)*2),&nx,&ny, smoothCos, 1); if (!smooth) { smoothness.push_back(1); for(int j=0; j<=numSides;j++) { normal[((k)*(numSides+1) + j)*4] = nx * cos(j*inc); normal[((k)*(numSides+1) + j)*4+1] = ny; normal[((k)*(numSides+1) + j)*4+2] = nx * sin(-j*inc); normal[((k)*(numSides+1) + j)*4+3] = 0.0f; vertex[((k)*(numSides+1) + j)*4] = p[(i+1)*2] * cos(j*inc); vertex[((k)*(numSides+1) + j)*4+1] = p[((i+1)*2)+1]; vertex[((k)*(numSides+1) + j)*4+2] = p[(i+1)*2] * sin(-j*inc); vertex[((k)*(numSides+1) + j)*4+3] = 1.0f; textco[((k)*(numSides+1) + j)*4] = ((j+0.0f)/numSides); textco[((k)*(numSides+1) + j)*4+1] = (i+1+0.0f)/(numP-1); textco[((k)*(numSides+1) + j)*4+2] = 0; textco[((k)*(numSides+1) + j)*4+3] = 1.0f; } k++; } else smoothness.push_back(0); } } unsigned int *faceIndex = (unsigned int *)malloc(sizeof(unsigned int) * (numP-1) * (numSides+1 ) * 6); unsigned int count = 0; k = 0; for (int i = 0; i < numP-1; ++i) { for (int j = 0; j < numSides; ++j) { /*if (i != 0 || p[0] != 0.0)*/ { faceIndex[count++] = k * (numSides+1) + j; faceIndex[count++] = (k+1) * (numSides+1) + j + 1; faceIndex[count++] = (k+1) * (numSides+1) + j; } /*if (i != numP-2 || p[(numP-1)*2] != 0.0)*/ { faceIndex[count++] = k * (numSides+1) + j; faceIndex[count++] = k * (numSides+1) + j + 1; faceIndex[count++] = (k+1) * (numSides+1) + j + 1; } } k++; k += smoothness[i]; } int numVertices = numP*2 * (numSides+1); mMyMesh[objId].numIndexes = count; glGenVertexArrays(1, &mMyMesh[objId].vao); glBindVertexArray(mMyMesh[objId].vao); GLuint buffers[4]; glGenBuffers(4, buffers); //vertex coordinates buffer glBindBuffer(GL_ARRAY_BUFFER, buffers[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * numVertices * 4, vertex, GL_STATIC_DRAW); glEnableVertexAttribArray(VSShaderLib::VERTEX_COORD_ATTRIB); glVertexAttribPointer(VSShaderLib::VERTEX_COORD_ATTRIB, 4, GL_FLOAT, 0, 0, 0); //texture coordinates buffer glBindBuffer(GL_ARRAY_BUFFER, buffers[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * numVertices * 4, textco, GL_STATIC_DRAW); glEnableVertexAttribArray(VSShaderLib::TEXTURE_COORD_ATTRIB); glVertexAttribPointer(VSShaderLib::TEXTURE_COORD_ATTRIB, 4, GL_FLOAT, 0, 0, 0); //normals buffer glBindBuffer(GL_ARRAY_BUFFER, buffers[2]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * numVertices * 4, normal, GL_STATIC_DRAW); glEnableVertexAttribArray(VSShaderLib::NORMAL_ATTRIB); glVertexAttribPointer(VSShaderLib::NORMAL_ATTRIB, 4, GL_FLOAT, 0, 0, 0); //index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[3]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mMyMesh[objId].numIndexes, faceIndex , GL_STATIC_DRAW); // unbind the VAO glBindVertexArray(0); mMyMesh[objId].type = GL_TRIANGLES; mMyMesh[objId].mat.ambient[0] = 0.2f; mMyMesh[objId].mat.ambient[1] = 0.2f; mMyMesh[objId].mat.ambient[2] = 0.2f; mMyMesh[objId].mat.ambient[3] = 1.0f; mMyMesh[objId].mat.diffuse[0] = 0.8f; mMyMesh[objId].mat.diffuse[1] = 0.8f; mMyMesh[objId].mat.diffuse[2] = 0.8f; mMyMesh[objId].mat.diffuse[3] = 1.0f; mMyMesh[objId].mat.specular[0] = 0.8f; mMyMesh[objId].mat.specular[1] = 0.8f; mMyMesh[objId].mat.specular[2] = 0.8f; mMyMesh[objId].mat.specular[3] = 1.0f; mMyMesh[objId].mat.shininess = 100.0f; }
void OGLGameObject::render(const ReferenceFrame& frame) { glUseProgram(shader); glBindBuffer(GL_ARRAY_BUFFER, vboID); // Positions glEnableVertexAttribArray(0); glVertexAttribPointer( 0, vertexData.getComponentCount(ObjectData::POSITION), GL_FLOAT, GL_FALSE, vertexData.getStride(ObjectData::POSITION), (void*)vertexData.getStartingOffset(ObjectData::POSITION) ); // Colors glEnableVertexAttribArray(1); glVertexAttribPointer( 1, vertexData.getComponentCount(ObjectData::COLOR), GL_FLOAT, GL_FALSE, vertexData.getStride(ObjectData::COLOR), (void*)vertexData.getStartingOffset(ObjectData::COLOR) ); // Normals if(vertexData.getComponentCount(ObjectData::NORMAL) > 0){ glEnableVertexAttribArray(2); glVertexAttribPointer( 2, vertexData.getComponentCount(ObjectData::NORMAL), GL_FLOAT, GL_FALSE, vertexData.getStride(ObjectData::NORMAL), (void*)vertexData.getStartingOffset(ObjectData::NORMAL) ); } switch(vertexData.getPrimitive()){ case ObjectData::TRIANGLES:{ glUniformMatrix4fv(transformMatrixUnif, 1, GL_FALSE, glm::value_ptr(frame.orientation)); glUniform4f(ambientIntensityUnif, material.getAmbient().r, material.getAmbient().g, material.getAmbient().b, material.getAmbient().a); glUniform4f(specularUnif, material.getSpecular().r, material.getSpecular().g, material.getSpecular().b, material.getSpecular().a); glUniform1f(shininessUnif, material.getShininess()); glDrawArrays(GL_TRIANGLES, 0, vertexData.getNumberOfVertices()); break; } case ObjectData::POINTS: glDrawArrays(GL_POINTS, 0, vertexData.getNumberOfVertices()); break; case ObjectData::LINES: glUniformMatrix4fv(transformMatrixUnif, 1, GL_FALSE, glm::value_ptr(frame.orientation)); glDrawArrays(GL_LINES, 0, vertexData.getNumberOfVertices()); break; } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glUseProgram(0); }
/** * Create a gear wheel. * * @param inner_radius radius of hole at center * @param outer_radius radius at center of teeth * @param width width of gear * @param teeth number of teeth * @param tooth_depth depth of tooth * * @return pointer to the constructed struct gear */ static struct gear * create_gear(GLfloat inner_radius, GLfloat outer_radius, GLfloat width, GLint teeth, GLfloat tooth_depth) { GLfloat r0, r1, r2; GLfloat da; GearVertex *v; struct gear *gear; double s[5], c[5]; GLfloat normal[3]; int cur_strip = 0; int i; /* Allocate memory for the gear */ gear = malloc(sizeof *gear); if (gear == NULL) return NULL; /* Calculate the radii used in the gear */ r0 = inner_radius; r1 = outer_radius - tooth_depth / 2.0; r2 = outer_radius + tooth_depth / 2.0; da = 2.0 * M_PI / teeth / 4.0; /* Allocate memory for the triangle strip information */ gear->nstrips = STRIPS_PER_TOOTH * teeth; gear->strips = calloc(gear->nstrips, sizeof (*gear->strips)); /* Allocate memory for the vertices */ gear->vertices = calloc(VERTICES_PER_TOOTH * teeth, sizeof(*gear->vertices)); v = gear->vertices; for (i = 0; i < teeth; i++) { /* Calculate needed sin/cos for varius angles */ sincos(i * 2.0 * M_PI / teeth, &s[0], &c[0]); sincos(i * 2.0 * M_PI / teeth + da, &s[1], &c[1]); sincos(i * 2.0 * M_PI / teeth + da * 2, &s[2], &c[2]); sincos(i * 2.0 * M_PI / teeth + da * 3, &s[3], &c[3]); sincos(i * 2.0 * M_PI / teeth + da * 4, &s[4], &c[4]); /* A set of macros for making the creation of the gears easier */ #define GEAR_POINT(r, da) { (r) * c[(da)], (r) * s[(da)] } #define SET_NORMAL(x, y, z) do { \ normal[0] = (x); normal[1] = (y); normal[2] = (z); \ } while(0) #define GEAR_VERT(v, point, sign) vert((v), p[(point)].x, p[(point)].y, (sign) * width * 0.5, normal) #define START_STRIP do { \ gear->strips[cur_strip].first = v - gear->vertices; \ } while(0); #define END_STRIP do { \ int _tmp = (v - gear->vertices); \ gear->strips[cur_strip].count = _tmp - gear->strips[cur_strip].first; \ cur_strip++; \ } while (0) #define QUAD_WITH_NORMAL(p1, p2) do { \ SET_NORMAL((p[(p1)].y - p[(p2)].y), -(p[(p1)].x - p[(p2)].x), 0); \ v = GEAR_VERT(v, (p1), -1); \ v = GEAR_VERT(v, (p1), 1); \ v = GEAR_VERT(v, (p2), -1); \ v = GEAR_VERT(v, (p2), 1); \ } while(0) struct point { GLfloat x; GLfloat y; }; /* Create the 7 points (only x,y coords) used to draw a tooth */ struct point p[7] = { GEAR_POINT(r2, 1), // 0 GEAR_POINT(r2, 2), // 1 GEAR_POINT(r1, 0), // 2 GEAR_POINT(r1, 3), // 3 GEAR_POINT(r0, 0), // 4 GEAR_POINT(r1, 4), // 5 GEAR_POINT(r0, 4), // 6 }; /* Front face */ START_STRIP; SET_NORMAL(0, 0, 1.0); v = GEAR_VERT(v, 0, +1); v = GEAR_VERT(v, 1, +1); v = GEAR_VERT(v, 2, +1); v = GEAR_VERT(v, 3, +1); v = GEAR_VERT(v, 4, +1); v = GEAR_VERT(v, 5, +1); v = GEAR_VERT(v, 6, +1); END_STRIP; /* Inner face */ START_STRIP; QUAD_WITH_NORMAL(4, 6); END_STRIP; /* Back face */ START_STRIP; SET_NORMAL(0, 0, -1.0); v = GEAR_VERT(v, 6, -1); v = GEAR_VERT(v, 5, -1); v = GEAR_VERT(v, 4, -1); v = GEAR_VERT(v, 3, -1); v = GEAR_VERT(v, 2, -1); v = GEAR_VERT(v, 1, -1); v = GEAR_VERT(v, 0, -1); END_STRIP; /* Outer face */ START_STRIP; QUAD_WITH_NORMAL(0, 2); END_STRIP; START_STRIP; QUAD_WITH_NORMAL(1, 0); END_STRIP; START_STRIP; QUAD_WITH_NORMAL(3, 1); END_STRIP; START_STRIP; QUAD_WITH_NORMAL(5, 3); END_STRIP; } gear->nvertices = (v - gear->vertices); /* Store the vertices in a vertex buffer object (VBO) */ glGenBuffers(1, &gear->vbo); glBindBuffer(GL_ARRAY_BUFFER, gear->vbo); glBufferData(GL_ARRAY_BUFFER, gear->nvertices * sizeof(GearVertex), gear->vertices, GL_STATIC_DRAW); return gear; }
void RenderingEngine::Initialize(const vector<ISurface*>& surfaces) { vector<ISurface*>::const_iterator surface; for (surface = surfaces.begin(); surface != surfaces.end(); ++surface) { // Create the VBO for the vertices. vector<float> vertices; (*surface)->GenerateVertices(vertices, VertexFlagsNormals); GLuint vertexBuffer; glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vertices[0]), &vertices[0], GL_STATIC_DRAW); // Create a VBO for the triangle indices. int triangleIndexCount = (*surface)->GetTriangleIndexCount(); vector<GLushort> triangleIndices(triangleIndexCount); (*surface)->GenerateTriangleIndices(triangleIndices); GLuint triangleIndexBuffer; glGenBuffers(1, &triangleIndexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangleIndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, triangleIndexCount * sizeof(GLushort), &triangleIndices[0], GL_STATIC_DRAW); // Create a VBO for the line indices. int lineIndexCount = (*surface)->GetTriangleIndexCount(); vector<GLushort> lineIndices(lineIndexCount); (*surface)->GenerateLineIndices(lineIndices); GLuint lineIndexBuffer; glGenBuffers(1, &lineIndexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lineIndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, lineIndexCount * sizeof(GLushort), &lineIndices[0], GL_STATIC_DRAW); Drawable drawable = { vertexBuffer, triangleIndexBuffer, lineIndexBuffer, triangleIndexCount, lineIndexBuffer }; m_drawables.push_back(drawable); } #ifndef MACOSX // Extract width and height from the color buffer. int width, height; glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height); // Create a depth buffer that has the same size as the color buffer. glGenRenderbuffersOES(1, &m_depthRenderbuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, m_depthRenderbuffer); glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height); // Create the framebuffer object. GLuint framebuffer; glGenFramebuffersOES(1, &framebuffer); glBindFramebufferOES(GL_FRAMEBUFFER_OES, framebuffer); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, m_colorRenderbuffer); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, m_depthRenderbuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, m_colorRenderbuffer); #endif // Set up various GL state. glEnableClientState(GL_VERTEX_ARRAY); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glShadeModel(GL_FLAT); glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); // Set up the material properties. vec4 ambient(0.2f, 0.2f, 0.2f, 1); vec4 specular(0.5f, 0.5f, 0.5f, 1); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient.Pointer()); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular.Pointer()); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 30.0f); m_translation = mat4::Translate(0, 0, -7); }
void piglit_init(int argc, char**argv) { GLuint tex; piglit_require_extension("GL_ARB_gpu_shader5"); glGenFramebuffers(1, &ms_fbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, ms_fbo); glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, tex); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGBA, 64, 64, GL_TRUE); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, tex, 0); if (!piglit_check_gl_error(GL_NO_ERROR)) { printf("fbo setup failed.\n"); piglit_report_result(PIGLIT_SKIP); } /* Test quantity varies from -1 to +1 over 64 pixels -- * so moving 1px changes its value by 1/32. */ draw_prog = piglit_build_simple_program( "#version 150\n" "uniform vec2 sample_pos;\n" "in vec2 p;\n" "out vec2 test;\n" "out vec2 ref;\n" "void main() {\n" " gl_Position = vec4(p, 0, 1);\n" " test = p;\n" " ref = p;\n" " ref.xy += sample_pos / 32;\n" "}\n", "#version 150\n" "#extension GL_ARB_gpu_shader5: require\n" "const int sample_id = 0;\n" "in vec2 test;\n" "in vec2 ref;\n" "void main() {\n" " gl_FragColor = vec4(" GAIN " * abs(\n" " interpolateAtSample(test, sample_id) - ref), 0, 1);\n" "}\n"); if (!draw_prog) { printf("draw_prog compile/link failed\n"); piglit_report_result(PIGLIT_FAIL); } test_prog = piglit_build_simple_program( "#version 150\n" "in vec2 p;\n" "void main() {\n" " gl_Position = vec4(p, 0, 1);\n" "}\n", "#version 150\n" "uniform sampler2DMS s;\n" "void main() {\n" " vec4 temp = \n" " texelFetch(s, ivec2(gl_FragCoord.xy), 0) +\n" " texelFetch(s, ivec2(gl_FragCoord.xy), 1) +\n" " texelFetch(s, ivec2(gl_FragCoord.xy), 2) +\n" " texelFetch(s, ivec2(gl_FragCoord.xy), 3);\n" " gl_FragColor = vec4(temp.x, 1-temp.y, temp.z, temp.w);\n" "}\n"); if (!test_prog) { printf("test_prog compile/link failed\n"); piglit_report_result(PIGLIT_FAIL); } sample_pos_loc = glGetUniformLocation(draw_prog, "sample_pos"); glUseProgram(test_prog); glUniform1i(glGetUniformLocation(test_prog, "s"), 0); if (!piglit_check_gl_error(GL_NO_ERROR)) { printf("shader setup failed\n"); piglit_report_result(PIGLIT_SKIP); } glGenVertexArrays(1, &vao); glBindVertexArray(vao); glEnableVertexAttribArray(0); glGenBuffers(1, &bo); glBindBuffer(GL_ARRAY_BUFFER, bo); glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid const *)0); }
static int initScene(scene_t *scene) { // load mesh if (!loadSimpleObjFile("gazebo.obj", &scene->vertices, &scene->vertexCount, &scene->indices, &scene->indexCount)) { fprintf(stderr, "Error loading obj file\n"); return 0; } glGenVertexArrays(1, &scene->vao); glBindVertexArray(scene->vao); glGenBuffers(1, &scene->vbo); glBindBuffer(GL_ARRAY_BUFFER, scene->vbo); glBufferData(GL_ARRAY_BUFFER, scene->vertexCount * sizeof(vertex_t), scene->vertices, GL_STATIC_DRAW); glGenBuffers(1, &scene->ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, scene->ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, scene->indexCount * sizeof(unsigned short), scene->indices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_t), (void*)offsetof(vertex_t, p)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(vertex_t), (void*)offsetof(vertex_t, t)); // create lightmap texture scene->w = 654; scene->h = 654; glGenTextures(1, &scene->lightmap); glBindTexture(GL_TEXTURE_2D, scene->lightmap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); unsigned char emissive[] = { 0, 0, 0, 255 }; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, emissive); // load shader const char *vp = "#version 150 core\n" "in vec3 a_position;\n" "in vec2 a_texcoord;\n" "uniform mat4 u_view;\n" "uniform mat4 u_projection;\n" "out vec2 v_texcoord;\n" "void main()\n" "{\n" "gl_Position = u_projection * (u_view * vec4(a_position, 1.0));\n" "v_texcoord = a_texcoord;\n" "}\n"; const char *fp = "#version 150 core\n" "in vec2 v_texcoord;\n" "uniform sampler2D u_lightmap;\n" "out vec4 o_color;\n" "void main()\n" "{\n" "o_color = vec4(texture(u_lightmap, v_texcoord).rgb, gl_FrontFacing ? 1.0 : 0.0);\n" "}\n"; const char *attribs[] = { "a_position", "a_texcoord" }; scene->program = loadProgram(vp, fp, attribs, 2); if (!scene->program) { fprintf(stderr, "Error loading shader\n"); return 0; } scene->u_view = glGetUniformLocation(scene->program, "u_view"); scene->u_projection = glGetUniformLocation(scene->program, "u_projection"); scene->u_lightmap = glGetUniformLocation(scene->program, "u_lightmap"); return 1; }
bool OGLES2RenderToTexture::DrawScreen() { /* We're going to do the following steps to create the effect. Texture 1 refers to the texture attached to the first FBO. Texture 2 refers to the texture attached to the second FBO. Frame 0 1. We bind the second frame buffer object so we can do things to it. 2. We draw two quads with Texture 1 applied. 3. We draw the trunk. 4. We make the back buffer current. 5. We draw 6 quads with Texture 2 applied. Frame 1 6. We bind the first frame buffer object so we can do things to it. 7. We draw two quads with Texture 2 applied. Texture 2 still contains the image from the last frame. 8. We draw the trunk. 9. We make the back buffer current. 10. We draw 6 quads with Texture 1 applied. Frame 2 11. We bind the second frame buffer object so we can do things to it. 12. We draw two quads with Texture 1 applied. Texture 1 still contains the image from the last frame. 13. We draw the trunk. 14. We make the back buffer current. 15. We draw 6 quads with Texture 2 applied. 16. We repeat steps 6 through to 16 for consecutive frames. */ /* Use the program created with the fragment and vertex shaders. */ glUseProgram(m_ShaderProgram.uiId); glBindBuffer(GL_ARRAY_BUFFER, m_uiVbo); glDisable(GL_CULL_FACE); glEnableVertexAttribArray(VERTEX_ARRAY); glEnableVertexAttribArray(TEXCOORD_ARRAY); glVertexAttribPointer(VERTEX_ARRAY, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 0); glVertexAttribPointer(TEXCOORD_ARRAY, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); /* Draw the fractal onto the current m_ui32Texture */ if(!RenderFractal()) return false; PVRTMat4 fMatrix; fMatrix = PVRTMat4::Identity(); /* Bind the projection model view matrix (PMVMatrix) to the associated uniform variable in the shader */ glUniformMatrix4fv(m_ShaderProgram.auiLoc[eMVPMatrix], 1, GL_FALSE, fMatrix.ptr()); // Clear the color and depth buffer glClearColor(0.6f, 0.8f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Set the viewport ot fill the screen. */ glViewport(0, 0, PVRShellGet(prefWidth), PVRShellGet(prefHeight)); /* Set up the matrix we are going to use to rotate and scale the 6 quads. */ PVRTMat4 fRotZ; fMatrix = PVRTMat4::Scale(0.8f *(float)PVRShellGet(prefHeight) / (float)PVRShellGet(prefWidth), 0.8f, 0.8f); fRotZ = PVRTMat4::RotationZ(1.047f); // glEnable(GL_BLEND); glBlendFunc(GL_DST_COLOR, GL_ONE); /* Bind the texture that we have rendered too.*/ glBindTexture(GL_TEXTURE_2D, m_auiTexture[m_i32CurrentFbo]); /* Draws 6 rotated quads */ for(int i = 0; i < 6; ++i) { // Set the transformationh matrix glUniformMatrix4fv(m_ShaderProgram.auiLoc[eMVPMatrix], 1, GL_FALSE, fMatrix.ptr()); // Draw the quad glDrawArrays(GL_TRIANGLE_STRIP, 5, 4); // Rotate the object by another 60 degrees. fMatrix = fMatrix * fRotZ; } // Swap the FBOs m_i32CurrentFbo = 1 - m_i32CurrentFbo; glBindBuffer(GL_ARRAY_BUFFER, 0); glDisableVertexAttribArray(VERTEX_ARRAY); glDisableVertexAttribArray(TEXCOORD_ARRAY); return true; }
static void spherical_draw(void* proj, GLuint v4Position, GLuint uViewMatrix, const GLfloat viewMatrix[16], GLuint v2Texture, GLuint uTextureMatrix, const GLfloat textureMatrix[16]) { spherical_map_t* sphere; GLfloat translateMatrix[16]; GLfloat projMatrix[16]; GLfloat mvpMatix[16]; GLint viewport[4]; GLint frontface[1]; GLfloat ratio; sphere = (spherical_map_t*)proj; glGetIntegerv(GL_FRONT_FACE, frontface); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CW); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindBuffer(GL_ARRAY_BUFFER, sphere->buffer[IDX_VERTEX_BUFFER]); glVertexAttribPointer(v4Position, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (const void*)0); glEnableVertexAttribArray(v4Position); glVertexAttribPointer(v2Texture, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (const void*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(v2Texture); glGetIntegerv(GL_VIEWPORT, viewport); ratio = 1.0f * viewport[2] / viewport[3] / (2 - sphere->vrmode); opengl_matrix_perspective(projMatrix, 90.0f, ratio, 0.01, 10.0f); // opengl_matrix_ortho(projMatrix, -0.7071f, 0.7071f, -0.7071f, 0.7071f, 1.0f, 0.0f); // opengl_matrix_ortho(projMatrix, -0.7071f * ratio, 0.7071f * ratio, -0.7071f, 0.7071f, -0.1f, -1.0f); opengl_matrix_multiply_mm(mvpMatix, projMatrix, viewMatrix); // left eye glViewport(viewport[0], viewport[1], viewport[2] / (2 - sphere->vrmode), viewport[3]); opengl_matrix_translate(translateMatrix, INTERPUPILLARY_DISTANCE/2, 0.0f, 0.0f); opengl_matrix_multiply_mm(projMatrix, translateMatrix, mvpMatix); glUniformMatrix4fv(uViewMatrix, 1, GL_FALSE, projMatrix); glUniformMatrix4fv(uTextureMatrix, 1, GL_FALSE, textureMatrix); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphere->buffer[IDX_INDEX_BUFFER]); glDrawElements(GL_TRIANGLES, N_INDEX_COUNT, GL_UNSIGNED_SHORT, (const void*)0); // right eye if (0 == sphere->vrmode) { glViewport(viewport[0] + viewport[2] / 2, viewport[1], viewport[2] / 2, viewport[3]); opengl_matrix_translate(translateMatrix, -INTERPUPILLARY_DISTANCE / 2, 0.0f, 0.0f); opengl_matrix_multiply_mm(projMatrix, translateMatrix, mvpMatix); glUniformMatrix4fv(uViewMatrix, 1, GL_FALSE, projMatrix); glUniformMatrix4fv(uTextureMatrix, 1, GL_FALSE, textureMatrix); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphere->buffer[IDX_INDEX_BUFFER]); glDrawElements(GL_TRIANGLES, N_INDEX_COUNT, GL_UNSIGNED_SHORT, (const void*)0); } glFrontFace(frontface[0]); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableVertexAttribArray(v4Position); glDisableVertexAttribArray(v2Texture); glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); }
/* Object draw function. * ARGUMENTS: * - object structure pointer: * vg4OBJ *Obj; * RETURNS: None. */ VOID MM3_RndObjDraw( mm3OBJ *Obj ) { INT i; INT loc, mtl; MATR M, MSave; for (i = 0; i < Obj->NumOfPrims; i++) { /* Build transform matrix */ MSave = MM3_RndMatrWorld; MM3_RndMatrWorld = MatrMulMatr(MM3_RndMatrWorld, Obj->Prims[i].M); M = MatrMulMatr(MM3_RndMatrWorld, MatrMulMatr(MM3_RndMatrView, MM3_RndMatrProj)); glLoadMatrixf(M.A[0]); /* glBegin(GL_LINES); glColor3d(1, 0, 0); glVertex3d(0, 0, 0); glVertex4d(1, 0, 0, 0); glColor3d(0, 1, 0); glVertex3d(0, 0, 0); glVertex4d(0, 1, 0, 0); glColor3d(0, 0, 1); glVertex3d(0, 0, 0); glVertex4d(0, 0, 1, 0); glEnd(); */ glUseProgram(MM3_RndPrg); mtl = Obj->Prims[i].MtlNo; if (mtl != -1) { if (MM3_RndMaterials[mtl].TexNo != 0) { glBindTexture(GL_TEXTURE_2D, MM3_RndMaterials[mtl].TexNo); if ((loc = glGetUniformLocation(MM3_RndPrg, "IsTexture")) != -1) glUniform1i(loc, 1); } else { if ((loc = glGetUniformLocation(MM3_RndPrg, "IsTexture")) != -1) glUniform1i(loc, 0); } if ((loc = glGetUniformLocation(MM3_RndPrg, "Ka")) != -1) glUniform3fv(loc, 1, &MM3_RndMaterials[mtl].Ka.X); if ((loc = glGetUniformLocation(MM3_RndPrg, "Kd")) != -1) glUniform3fv(loc, 1, &MM3_RndMaterials[mtl].Kd.X); if ((loc = glGetUniformLocation(MM3_RndPrg, "Ks")) != -1) glUniform3fv(loc, 1, &MM3_RndMaterials[mtl].Ks.X); if ((loc = glGetUniformLocation(MM3_RndPrg, "Ph")) != -1) glUniform1f(loc, MM3_RndMaterials[mtl].Ph); if ((loc = glGetUniformLocation(MM3_RndPrg, "Trans")) != -1) glUniform1f(loc, MM3_RndMaterials[mtl].Trans); } /* Setup global variables */ if ((loc = glGetUniformLocation(MM3_RndPrg, "MatrWVP")) != -1) glUniformMatrix4fv(loc, 1, FALSE, M.A[0]); if ((loc = glGetUniformLocation(MM3_RndPrg, "MatrWorld")) != -1) glUniformMatrix4fv(loc, 1, FALSE, MM3_RndMatrWorld.A[0]); if ((loc = glGetUniformLocation(MM3_RndPrg, "MatrView")) != -1) glUniformMatrix4fv(loc, 1, FALSE, MM3_RndMatrView.A[0]); if ((loc = glGetUniformLocation(MM3_RndPrg, "MatrProj")) != -1) glUniformMatrix4fv(loc, 1, FALSE, MM3_RndMatrProj.A[0]); if ((loc = glGetUniformLocation(MM3_RndPrg, "Time")) != -1) glUniform1f(loc, MM3_Anim.Time); if ((loc = glGetUniformLocation(MM3_RndPrg, "PartNo")) != -1) glUniform1i(loc, i); /* Activete primitive vertex array */ glBindVertexArray(Obj->Prims[i].VA); /* Activete primitive index buffer */ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Obj->Prims[i].IBuf); /* Draw primitive */ glDrawElements(GL_TRIANGLES, Obj->Prims[i].NumOfI, GL_UNSIGNED_INT, NULL); glUseProgram(0); MM3_RndMatrWorld = MSave; } } /* End of 'VG4_RndObjDraw' function */
void ColoredPyramid::initialize() { GLfloat hH = height/2.0f; GLfloat hW = width/2.0f; buildShaderProgram(); GLuint VBO, IBO; glGenVertexArrays (1, &vertexArrayObject); glBindVertexArray( vertexArrayObject ); vector<VertexData> v; v.push_back( VertexData( vec3( 0.0f, hH, 0.0f), vec4( 1.0f, 0.0f, 0.0f, 1.0f ))); v.push_back( VertexData( vec3(-hW, -hH, hW), vec4( 0.0f, 1.0f, 0.0f, 1.0f ))); v.push_back( VertexData( vec3( hW, -hH, hW), vec4( 0.0f, 0.0f, 1.0f, 1.0f ))); v.push_back( VertexData( vec3( hW, -hH, -hW), vec4( 1.0f, 1.0f, 0.0f, 1.0f ))); v.push_back( VertexData( vec3(-hW, -hH, -hW), vec4( 0.0f, 1.0f, 1.0f, 1.0f ))); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, v.size() * sizeof(VertexData), &v[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), 0); glEnableVertexAttribArray(0); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(VertexData),(const GLvoid*)sizeof(vec3)); glEnableVertexAttribArray(2); vector<unsigned int> i; i.push_back(0); i.push_back(1); i.push_back(2); i.push_back(0); i.push_back(2); i.push_back(3); i.push_back(0); i.push_back(3); i.push_back(4); i.push_back(0); i.push_back(4); i.push_back(1); i.push_back(4); i.push_back(2); i.push_back(1); i.push_back(4); i.push_back(3); i.push_back(2); numberOfIndices = sizeof( i ); glGenBuffers(1, &IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, i.size() * sizeof(unsigned int), &i[0], GL_STATIC_DRAW); } // end initialize
void InitShaders() { bool loadFromFile = false; instancingShader = gltLoadShaderPair("instancing.vs","instancing.fs", loadFromFile); glLinkProgram(instancingShader); glUseProgram(instancingShader); angle_loc = glGetUniformLocation(instancingShader, "angle"); ModelViewMatrix = glGetUniformLocation(instancingShader, "ModelViewMatrix"); ProjectionMatrix = glGetUniformLocation(instancingShader, "ProjectionMatrix"); uniform_texture_diffuse = glGetUniformLocation(instancingShader, "Diffuse"); GLuint offset = 0; glGenBuffers(1, &cube_vbo); glBindBuffer(GL_ARRAY_BUFFER, cube_vbo); instance_positions_ptr = (GLfloat*)new float[NUM_OBJECTS*4]; instance_quaternion_ptr = (GLfloat*)new float[NUM_OBJECTS*4]; int index=0; for (int i=0;i<NUM_OBJECTS_X;i++) { for (int j=0;j<NUM_OBJECTS_Y;j++) { for (int k=0;k<NUM_OBJECTS_Z;k++) { instance_positions_ptr[index*4]=-(i-NUM_OBJECTS_X/2)*10; instance_positions_ptr[index*4+1]=-(j-NUM_OBJECTS_Y/2)*10; instance_positions_ptr[index*4+2]=-k*10; instance_positions_ptr[index*4+3]=1; instance_quaternion_ptr[index*4]=0; instance_quaternion_ptr[index*4+1]=0; instance_quaternion_ptr[index*4+2]=0; instance_quaternion_ptr[index*4+3]=1; index++; } } } int size = sizeof(cube_vertices) + POSITION_BUFFER_SIZE+ORIENTATION_BUFFER_SIZE; char* bla = (char*)malloc(size); int szc = sizeof(cube_vertices); memcpy(bla,&cube_vertices[0],szc); memcpy(bla+sizeof(cube_vertices),instance_positions_ptr,POSITION_BUFFER_SIZE); memcpy(bla+sizeof(cube_vertices)+POSITION_BUFFER_SIZE,instance_quaternion_ptr,ORIENTATION_BUFFER_SIZE); glBufferData(GL_ARRAY_BUFFER, size, bla, GL_DYNAMIC_DRAW);//GL_STATIC_DRAW); ///initialize parts of the buffer #ifdef _USE_SUB_DATA glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(cube_vertices)+ 16384, bla);//cube_vertices); #endif char* dest= (char*)glMapBuffer( GL_ARRAY_BUFFER,GL_WRITE_ONLY);//GL_WRITE_ONLY memcpy(dest,cube_vertices,sizeof(cube_vertices)); //memcpy(dest+sizeof(cube_vertices),instance_colors,sizeof(instance_colors)); glUnmapBuffer( GL_ARRAY_BUFFER); writeTransforms(); /* glBufferSubData(GL_ARRAY_BUFFER, sizeof(cube_vertices) + sizeof(instance_colors), POSITION_BUFFER_SIZE, instance_positions_ptr); glBufferSubData(GL_ARRAY_BUFFER, sizeof(cube_vertices) + sizeof(instance_colors)+POSITION_BUFFER_SIZE,ORIENTATION_BUFFER_SIZE , instance_quaternion_ptr); */ glGenVertexArrays(1, &cube_vao); glBindVertexArray(cube_vao); glBindBuffer(GL_ARRAY_BUFFER, cube_vbo); glBindVertexArray(0); glGenBuffers(1, &index_vbo); int indexBufferSize = sizeof(cube_indices); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_vbo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBufferSize, NULL, GL_STATIC_DRAW); glBufferSubData(GL_ELEMENT_ARRAY_BUFFER,0,indexBufferSize,cube_indices); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER,0); glBindVertexArray(0); }
static void ReadVerts(const char* filename) { FILE* infile = fopen(filename, "rb"); pezCheck(infile != 0, "Can't read file: %s\n", filename); glGenVertexArrays(1, &Scene.StatueVao); glBindVertexArray(Scene.StatueVao); fread(&Scene.StatueVertexCount, 1, 4, infile); int vertexStride = sizeof(float) * 3; GLsizeiptr positionsTotalSize = Scene.StatueVertexCount * vertexStride; GLfloat* positionsBuffer = (GLfloat*) malloc(positionsTotalSize); GLsizeiptr normalsTotalSize = Scene.StatueVertexCount * vertexStride; GLfloat* normalsBuffer = (GLfloat*) malloc(normalsTotalSize); fread(positionsBuffer, 1, positionsTotalSize, infile); fread(normalsBuffer, 1, normalsTotalSize, infile); fclose(infile); GLuint positionsHandle; glGenBuffers(1, &positionsHandle); glBindBuffer(GL_ARRAY_BUFFER, positionsHandle); glBufferData(GL_ARRAY_BUFFER, positionsTotalSize, positionsBuffer, GL_STATIC_DRAW); GLuint normalsHandle; glGenBuffers(1, &normalsHandle); glBindBuffer(GL_ARRAY_BUFFER, normalsHandle); glBufferData(GL_ARRAY_BUFFER, normalsTotalSize, normalsBuffer, GL_STATIC_DRAW); // Load AO data from point cloud // https://renderman.pixar.com/forum/docs/RPS_16/index.php?url=ptcloudApi.php#intro char* ptcFile = "../Cover/PreTess/City.ptc"; Scene.PointCloud = PtcSafeOpenPointCloudFile(ptcFile); pezCheck(Scene.PointCloud != 0, "Unable to open point cloud '%s'", ptcFile); GLsizeiptr occlusionsTotalSize = sizeof(float) * Scene.StatueVertexCount; float* occlusionsBuffer = (float*) malloc(occlusionsTotalSize); { float* pVertex = positionsBuffer; float* pNormal = normalsBuffer; float* pOcclusion = occlusionsBuffer; float normal[] = {0, 1, 0}; for (int i = 0; i < Scene.StatueVertexCount; i++) { pNormal[0] *= -1; pNormal[1] *= -1; pNormal[2] *= -1; *pOcclusion = 0; int retval = PtcGetNearestPointsData(Scene.PointCloud, pVertex, pNormal, AO_MaxDist, AO_NumPoints, pOcclusion); pVertex += 3; pNormal += 3; pOcclusion++; } } free(normalsBuffer); free(positionsBuffer); // Create VBO for AO data GLuint occlusionsHandle; glGenBuffers(1, &occlusionsHandle); glBindBuffer(GL_ARRAY_BUFFER, occlusionsHandle); glBufferData(GL_ARRAY_BUFFER, occlusionsTotalSize, occlusionsBuffer, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, positionsHandle); glEnableVertexAttribArray(PositionSlot); glVertexAttribPointer(PositionSlot, 3, GL_FLOAT, 0, vertexStride, nil); glBindBuffer(GL_ARRAY_BUFFER, normalsHandle); glEnableVertexAttribArray(NormalSlot); glVertexAttribPointer(NormalSlot, 3, GL_FLOAT, 0, vertexStride, nil); pezCheck(glGetError() == GL_NO_ERROR, "OpenGL error.\n"); if (OcclusionSlot > -1) { glBindBuffer(GL_ARRAY_BUFFER, occlusionsHandle); glEnableVertexAttribArray(OcclusionSlot); glVertexAttribPointer(OcclusionSlot, 1, GL_FLOAT, 0, sizeof(float), nil); } pezCheck(glGetError() == GL_NO_ERROR, "OpenGL error.\n"); // Create VAO for the floor float minX = -3.3f, maxX = +3.3f; float minY = -3.0f, maxY = +3.0f; float floorZ = 0; int floorRows = 32; int floorCols = 32; AO_MaxDist = 0.05f; AO_NumPoints = 1; int floorVertexCount = (floorRows + 1) * (floorCols + 1); GLsizeiptr interleavedTotalSize = sizeof(float) * 4 * floorVertexCount; float* interleavedBuffer = (float*) malloc(interleavedTotalSize); float dx = (maxX - minX) / floorRows; float dy = (maxY - minY) / floorCols; float* pBuffer = interleavedBuffer; int writtenVerts = 0; for (float x = minX; x < maxX + dx / 2; x += dx) { for (float y = minY; y < maxY + dy / 2; y += dy) { *(pBuffer + 0) = x; *(pBuffer + 1) = floorZ; *(pBuffer + 2) = y; float pNormal[] = {0, 1, 0}; *(pBuffer + 3) = 0.5f; PtcGetNearestPointsData(Scene.PointCloud, pBuffer, pNormal, AO_MaxDist, AO_NumPoints, pBuffer + 3); pBuffer += 4; ++writtenVerts; } } pezCheck(writtenVerts == floorVertexCount, "Internal error."); glGenVertexArrays(1, &Scene.FloorVao); glBindVertexArray(Scene.FloorVao); GLuint interleavedHandle; glGenBuffers(1, &interleavedHandle); glBindBuffer(GL_ARRAY_BUFFER, interleavedHandle); glBufferData(GL_ARRAY_BUFFER, interleavedTotalSize, interleavedBuffer, GL_STATIC_DRAW); vertexStride = 16; glEnableVertexAttribArray(PositionSlot); glVertexAttribPointer(PositionSlot, 3, GL_FLOAT, 0, vertexStride, nil); if (OcclusionSlot > -1) { glEnableVertexAttribArray(OcclusionSlot); glVertexAttribPointer(OcclusionSlot, 1, GL_FLOAT, 0, vertexStride, pv(12)); } free(interleavedBuffer); Scene.FloorIndexCount = floorRows * floorCols * 4; int indicesTotalSize = sizeof(int) * Scene.FloorIndexCount; int* indicesBuffer = (int*) malloc(indicesTotalSize); int* pIndex = indicesBuffer; int n = 0; for (int i = 0; i < floorRows; ++i) { for (int j = 0; j < floorCols; ++j) { int A = n++; int B = A + 1; int C = A + floorCols + 1; int D = B + floorCols + 1; *pIndex++ = A; *pIndex++ = B; *pIndex++ = D; *pIndex++ = C; } n++; } GLuint indicesHandle; glGenBuffers(1, &indicesHandle); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesTotalSize, indicesBuffer, GL_STATIC_DRAW); free(indicesBuffer); }
void SceneMesh::renderPlyMesh() { glBindVertexArray(vertexArrayId); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, plyVertexBuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, plyColorBuffer); glVertexAttribPointer( 1, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, plyNormalBuffer); glVertexAttribPointer( 2, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); //if (rType == Mesh) { // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, plyIndexBuffer); glDrawElements( GL_TRIANGLES, // mode numPlyMeshIndices, // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); } /*else { glEnable(GL_PROGRAM_POINT_SIZE); glPointSize(5); glDrawArrays(GL_POINTS, 0, numPlyMeshIndices); glDisable(GL_PROGRAM_POINT_SIZE); }*/ glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); }
void L_ParticleEffect::RenderPointSprites(SurfaceAnim *pSurf, int start, int count) { pSurf->Bind(); glBlendFunc( GL_SRC_ALPHA, GL_ONE); //this point sprite code was based on code from http://www.71squared.com/2009/05/iphone-game-programming-tutorial-8-particle-emitter/ which //was based on some cocos2d code I think -Seth glBindBuffer(GL_ARRAY_BUFFER, L_ParticleMem::pointSpriteBufferID); CHECK_GL_ERROR(); glBufferData(GL_ARRAY_BUFFER, sizeof(PointSprite)*count, &L_ParticleMem::pointSpriteArray[0], GL_DYNAMIC_DRAW); CHECK_GL_ERROR(); glEnable(GL_BLEND); // Enable and configure point sprites which we are going to use for our particles glEnable(GL_POINT_SPRITE_OES); CHECK_GL_ERROR(); glTexEnvi( GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE ); CHECK_GL_ERROR(); // Enable vertex arrays and bind to the vertices VBO which has been created glEnableClientState(GL_VERTEX_ARRAY); CHECK_GL_ERROR(); glBindBuffer(GL_ARRAY_BUFFER, L_ParticleMem::pointSpriteBufferID); CHECK_GL_ERROR(); // Configure the vertex pointer which will use the vertices VBO glVertexPointer(2, GL_FLOAT, sizeof(PointSprite), 0); CHECK_GL_ERROR(); // Enable the point size array glEnableClientState(GL_POINT_SIZE_ARRAY_OES); // Configure the point size pointer which will use the currently bound VBO. PointSprite contains // both the location of the point as well as its size, so the config below tells the point size // pointer where in the currently bound VBO it can find the size for each point glPointSizePointerOES(GL_FLOAT,sizeof(PointSprite),(GLvoid*) (sizeof(GL_FLOAT)*2)); // Enable the use of the color array glEnableClientState(GL_COLOR_ARRAY); // Configure the color pointer specifying how many values there are for each color and their type glColorPointer(4,GL_UNSIGNED_BYTE,sizeof(PointSprite),(GLvoid*) (sizeof(GL_FLOAT)*3)); // Now that all of the VBOs have been used to configure the vertices, pointer size and color // use glDrawArrays to draw the points //NOTE: It crashes here on the WebOS GLES windows emulator .. but runs on the device. driver bug I guess -Seth //Another note: It also can crash a Touchpad so.. not going to use this optimized point sprite stuff for webos :( glDrawArrays(GL_POINTS, start, count); CHECK_GL_ERROR(); // Unbind the current VBO glBindBuffer(GL_ARRAY_BUFFER, 0); CHECK_GL_ERROR(); // Disable the client states which have been used incase the next draw function does // not need or use them glDisableClientState(GL_POINT_SIZE_ARRAY_OES); glDisableClientState(GL_COLOR_ARRAY); CHECK_GL_ERROR(); glDisable(GL_POINT_SPRITE_OES); CHECK_GL_ERROR(); glDisableClientState(GL_POINT_SIZE_ARRAY_OES); glDisableClientState(GL_COLOR_ARRAY); CHECK_GL_ERROR(); glDisable(GL_POINT_SPRITE_OES); glDisable(GL_BLEND); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); CHECK_GL_ERROR(); }
void SceneMesh::loadBuffers() { if (type == OBJ) { const int numGroups = mesh->numGroups; const int numMaterials = mesh->numMaterials; vertexBuffers = new GLuint[numGroups]; normalBuffers = new GLuint[numGroups]; uvBuffers = new GLuint[numGroups]; indexBuffers = new GLuint[numGroups]; //vertexArrayIds = new GLuint[numGroups]; textureIds = new GLuint[numMaterials]; glGenVertexArrays(1, &vertexArrayId); glBindVertexArray(vertexArrayId); //glBindFramebuffer(GL_FRAMEBUFFER, 0); for (int i = 0; i < numGroups; i++) { const Group g = mesh->groups[i]; const int numVertex = g.vertices.size(); const int numNormal = g.normals.size(); const int numUvs = g.uvs.size(); const int numIndices = g.indices.size(); glGenBuffers(1, &vertexBuffers[i]); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffers[i]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * numVertex * 3, &g.vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &normalBuffers[i]); glBindBuffer(GL_ARRAY_BUFFER, normalBuffers[i]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * numNormal * 3, &g.normals[0], GL_STATIC_DRAW); glGenBuffers(1, &uvBuffers[i]); glBindBuffer(GL_ARRAY_BUFFER, uvBuffers[i]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * numUvs * 2, &g.uvs[0], GL_STATIC_DRAW); glGenBuffers(1, &indexBuffers[i]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffers[i]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndices * sizeof(int), &g.indices[0], GL_STATIC_DRAW); } for (int i = 0; i < numMaterials; i++) { char textureFilePath[256]; sprintf_s(textureFilePath, "%s%s", dataPath, mesh->materials[i].map_Kd); textureIds[i] = TextureLoader::loadTexture(textureFilePath); } numMeshGroups = mesh->numGroups; numMeshMaterials = mesh->numMaterials; for (int groupId = 0; groupId < numMeshGroups; groupId++) { int i = 0; for (i = 0; i < numMaterials; i++) { if (strcmp(mesh->groups[groupId].mat.tag, mesh->materials[i].tag) == 0) { textureIdList.push_back(i); break; } } if (i == numMaterials) textureIdList.push_back(-1); numIndicesList.push_back(mesh->groups[groupId].indices.size()); } // Deleting mesh data from Host's heap. The copy of mesh data is transferred to the GPU. //delete mesh; } else if (type == PLY) { glGenVertexArrays(1, &vertexArrayId); glBindVertexArray(vertexArrayId); const int numVertex = plyMesh->vertices.size(); const int numNormal = plyMesh->normals.size(); const int numColors = plyMesh->colors.size(); const int numIndices = plyMesh->indices.size(); glGenBuffers(1, &plyVertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, plyVertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * numVertex * 3, &plyMesh->vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &plyNormalBuffer); glBindBuffer(GL_ARRAY_BUFFER, plyNormalBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * numNormal * 3, &plyMesh->normals[0], GL_STATIC_DRAW); glGenBuffers(1, &plyColorBuffer); glBindBuffer(GL_ARRAY_BUFFER, plyColorBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * numColors * 3, &plyMesh->colors[0], GL_STATIC_DRAW); glGenBuffers(1, &plyIndexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, plyIndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndices * sizeof(unsigned int), &plyMesh->indices[0], GL_STATIC_DRAW); numPlyMeshIndices = plyMesh->indices.size(); // Deleting mesh data from Host's heap. The copy of mesh data is transferred to the GPU. //delete plyMesh; } }
void setup_vertex_position_buffer_object(void) { glGenBuffers(1, &vertex_position_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_position_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * trig.VertexCount(), &trig.Vertices()[0], GL_STATIC_DRAW); }
void init(void) { // vertex buffer object, used for uploading the geometry unsigned int vertexBufferObjID; unsigned int bunnyIndexBufferObjID; unsigned int bunnyNormalBufferObjID; unsigned int bunnyTexCoordBufferObjID; GLuint colorBufferObjID; model = LoadModel("bunnyplus.obj"); dumpInfo(); // GL inits glClearColor(1,0.2,0.5,0); //glFrontFace(GL_CW); glEnable(GL_DEPTH_TEST); //glEnable(GL_CULL_FACE); printError("GL inits"); // Load and compile shader program = loadShaders("lab2-5.vert", "lab2-5.frag"); printError("init shader"); // Upload geometry to the GPU: // Allocate and activate Vertex Array Object glGenVertexArrays(1, &vertexArrayObjID); glBindVertexArray(vertexArrayObjID); // Allocate Vertex Buffer Objects glGenBuffers(1, &vertexBufferObjID); // position glGenBuffers(1, &colorBufferObjID); // color glGenBuffers(1, &bunnyIndexBufferObjID); // index glGenBuffers(1, &bunnyNormalBufferObjID); // normal glGenBuffers(1, &bunnyTexCoordBufferObjID); // tex coords // VBO for vertex data glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID); glBufferData(GL_ARRAY_BUFFER, model->numVertices * 3 * sizeof(GLfloat), model->vertexArray, GL_STATIC_DRAW); glVertexAttribPointer(glGetAttribLocation(program, "in_Position"), 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(glGetAttribLocation(program, "in_Position")); // VBO for normal data glBindBuffer(GL_ARRAY_BUFFER, bunnyNormalBufferObjID); glBufferData(GL_ARRAY_BUFFER, model->numVertices * 3 * sizeof(GLfloat), model->normalArray, GL_STATIC_DRAW); glVertexAttribPointer(glGetAttribLocation(program, "in_Normal"), 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(glGetAttribLocation(program, "in_Normal")); // Index data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bunnyIndexBufferObjID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, model->numIndices*sizeof(GLuint), model->indexArray, GL_STATIC_DRAW); // Tex coord data if (model->texCoordArray != NULL) { glBindBuffer(GL_ARRAY_BUFFER, bunnyTexCoordBufferObjID); glBufferData(GL_ARRAY_BUFFER, model->numVertices * 2 * sizeof(GLfloat), model->texCoordArray, GL_STATIC_DRAW); glVertexAttribPointer(glGetAttribLocation(program, "inTexCoord"), 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(glGetAttribLocation(program, "inTexCoord")); // Load texture glUniform1i(glGetUniformLocation(program, "texUnit"), 0); // Texture unit 0 LoadTGATextureSimple("conc.tga", &texture); // } // Upload projection matrix glUniformMatrix4fv(glGetUniformLocation(program, "projMatrix"), 1, GL_TRUE, projectionMatrix); // Upload camera matrix mat4 cameraMatrix = lookAt(10, 10, 10, 0, 0, 0, 0, 1, 0); glUniformMatrix4fv(glGetUniformLocation(program, "cameraMatrix"), 1, GL_TRUE, cameraMatrix.m); // End of upload of geometry printError("init arrays"); }