/*!**************************************************************************** @Function InitView @Return bool true if no error occured @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES3ShadowVolumes::InitView() { CPVRTString ErrorStr; /* Initialize VBO data */ LoadVbos(); /* Load textures */ if (!LoadTextures(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } /* Load and compile the shaders & link programs */ if (!LoadShaders(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Set the sampler2D uniforms to corresponding texture units glUseProgram(m_BaseShader.uiId); glUniform1i(glGetUniformLocation(m_BaseShader.uiId, "sTexture"), 0); /* Initialise an array to lookup the textures for each material in the scene. */ m_puiTextures = new GLuint[m_Scene.nNumMaterial]; for(unsigned int i = 0; i < m_Scene.nNumMaterial; ++i) { m_puiTextures[i] = 0; SPODMaterial* pMaterial = &m_Scene.pMaterial[i]; if (!strcmp(pMaterial->pszName, "background")) { m_puiTextures[i] = m_uiBackgroundTex; } else if (!strcmp(pMaterial->pszName, "rust")) { m_puiTextures[i] = m_uiRustTex; } } // Go through the object type and find out how many shadows we are going to need m_ui32NoOfShadows = 0; for (int i = 0; i < eNumMeshes; ++i) { if(m_i32ObjectType[i] != eDoesntCast) ++m_ui32NoOfShadows; } // Build the shadow volumes and meshes // Create the number of shadow meshes and volumes we require m_pShadowMesh = new PVRTShadowVolShadowMesh[m_ui32NoOfShadows]; m_pShadowVol = new PVRTShadowVolShadowVol [m_ui32NoOfShadows]; // Create the array that stores the SPODNode ID for each shadow m_pui32MeshIndex = new unsigned int[m_ui32NoOfShadows]; // Go through the meshes and initialise the shadow meshes, volumes and mesh index for each requried shadow int i32Index = 0; for (int i = 0; i < eNumMeshes; ++i) { if(m_i32ObjectType[i] != eDoesntCast) { m_pui32MeshIndex[i32Index] = i; SPODNode* pNode = &m_Scene.pNode[i]; /* This function will take the POD mesh referenced by the current node and generate a new mesh suitable for creating shadow volumes and the shadow volume itself. */ BuildShadowVolume(&m_pShadowMesh[i32Index], &m_pShadowVol[i32Index], &m_Scene.pMesh[pNode->nIdx]); /* The function will initialise the shadow volume with regard to the meshes current transformation and the light position. As the light position is fixed this is only done once for static objects where as dynamic objects are updated every frame. */ BuildVolume(i32Index, &m_vLightPosWorld); ++i32Index; } } // Is the screen rotated? bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); /* Initialize Print3D */ if(m_Print3D.SetTextures(0,PVRShellGet(prefWidth),PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } // Calculate the view matrix PVRTVec3 vFrom, vTo; float fFOV; // We can get the camera position, target and field of view (fov) with GetCamera() fFOV = m_Scene.GetCameraPos( vFrom, vTo, 0); m_mView = PVRTMat4::LookAtRH(vFrom, vTo, PVRTVec3(0, 1, 0)); // Calculate the projection matrix m_mProjection = PVRTMat4::PerspectiveFovRH(fFOV, (float)PVRShellGet(prefWidth)/(float)PVRShellGet(prefHeight), CAM_NEAR, CAM_FAR, PVRTMat4::OGL, bRotate); /* Set OpenGL ES render states needed for this training course */ // Enable backface culling and depth test glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); // Use a nice bright blue as clear colour glClearColor(0.6f, 0.8f, 1.0f, 1.0f); glClearStencil(0); m_ulTimePrev = PVRShellGetTime(); return true; }
mitk::ShaderRepository::ShaderRepository() { LoadShaders(); }
void SceneText::Init() { // Black background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glGenVertexArrays(1, &m_vertexArrayID); glBindVertexArray(m_vertexArrayID); m_programID = LoadShaders( "Shader//Texture.vertexshader", "Shader//Text.fragmentshader" ); // Get a handle for our uniform m_parameters[U_MVP] = glGetUniformLocation(m_programID, "MVP"); //m_parameters[U_MODEL] = glGetUniformLocation(m_programID, "M"); //m_parameters[U_VIEW] = glGetUniformLocation(m_programID, "V"); m_parameters[U_MODELVIEW] = glGetUniformLocation(m_programID, "MV"); m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE] = glGetUniformLocation(m_programID, "MV_inverse_transpose"); m_parameters[U_MATERIAL_AMBIENT] = glGetUniformLocation(m_programID, "material.kAmbient"); m_parameters[U_MATERIAL_DIFFUSE] = glGetUniformLocation(m_programID, "material.kDiffuse"); m_parameters[U_MATERIAL_SPECULAR] = glGetUniformLocation(m_programID, "material.kSpecular"); m_parameters[U_MATERIAL_SHININESS] = glGetUniformLocation(m_programID, "material.kShininess"); m_parameters[U_LIGHTENABLED] = glGetUniformLocation(m_programID, "lightEnabled"); m_parameters[U_NUMLIGHTS] = glGetUniformLocation(m_programID, "numLights"); m_parameters[U_LIGHT0_TYPE] = glGetUniformLocation(m_programID, "lights[0].type"); m_parameters[U_LIGHT0_POSITION] = glGetUniformLocation(m_programID, "lights[0].position_cameraspace"); m_parameters[U_LIGHT0_COLOR] = glGetUniformLocation(m_programID, "lights[0].color"); m_parameters[U_LIGHT0_POWER] = glGetUniformLocation(m_programID, "lights[0].power"); m_parameters[U_LIGHT0_KC] = glGetUniformLocation(m_programID, "lights[0].kC"); m_parameters[U_LIGHT0_KL] = glGetUniformLocation(m_programID, "lights[0].kL"); m_parameters[U_LIGHT0_KQ] = glGetUniformLocation(m_programID, "lights[0].kQ"); m_parameters[U_LIGHT0_SPOTDIRECTION] = glGetUniformLocation(m_programID, "lights[0].spotDirection"); m_parameters[U_LIGHT0_COSCUTOFF] = glGetUniformLocation(m_programID, "lights[0].cosCutoff"); m_parameters[U_LIGHT0_COSINNER] = glGetUniformLocation(m_programID, "lights[0].cosInner"); m_parameters[U_LIGHT0_EXPONENT] = glGetUniformLocation(m_programID, "lights[0].exponent"); m_parameters[U_LIGHT1_TYPE] = glGetUniformLocation(m_programID, "lights[1].type"); m_parameters[U_LIGHT1_POSITION] = glGetUniformLocation(m_programID, "lights[1].position_cameraspace"); m_parameters[U_LIGHT1_COLOR] = glGetUniformLocation(m_programID, "lights[1].color"); m_parameters[U_LIGHT1_POWER] = glGetUniformLocation(m_programID, "lights[1].power"); m_parameters[U_LIGHT1_KC] = glGetUniformLocation(m_programID, "lights[1].kC"); m_parameters[U_LIGHT1_KL] = glGetUniformLocation(m_programID, "lights[1].kL"); m_parameters[U_LIGHT1_KQ] = glGetUniformLocation(m_programID, "lights[1].kQ"); m_parameters[U_LIGHT1_SPOTDIRECTION] = glGetUniformLocation(m_programID, "lights[1].spotDirection"); m_parameters[U_LIGHT1_COSCUTOFF] = glGetUniformLocation(m_programID, "lights[1].cosCutoff"); m_parameters[U_LIGHT1_COSINNER] = glGetUniformLocation(m_programID, "lights[1].cosInner"); m_parameters[U_LIGHT1_EXPONENT] = glGetUniformLocation(m_programID, "lights[1].exponent"); // Get a handle for our "colorTexture" uniform m_parameters[U_COLOR_TEXTURE_ENABLED] = glGetUniformLocation(m_programID, "colorTextureEnabled"); m_parameters[U_COLOR_TEXTURE] = glGetUniformLocation(m_programID, "colorTexture"); // Get a handle for our "textColor" uniform m_parameters[U_TEXT_ENABLED] = glGetUniformLocation(m_programID, "textEnabled"); m_parameters[U_TEXT_COLOR] = glGetUniformLocation(m_programID, "textColor"); // Use our shader glUseProgram(m_programID); lights[0].type = Light::LIGHT_DIRECTIONAL; lights[0].position.Set(0, 20, 0); lights[0].color.Set(1, 1, 1); lights[0].power = 1; lights[0].kC = 1.f; lights[0].kL = 0.01f; lights[0].kQ = 0.001f; lights[0].cosCutoff = cos(Math::DegreeToRadian(45)); lights[0].cosInner = cos(Math::DegreeToRadian(30)); lights[0].exponent = 3.f; lights[0].spotDirection.Set(0.f, 1.f, 0.f); lights[1].type = Light::LIGHT_DIRECTIONAL; lights[1].position.Set(1, 1, 0); lights[1].color.Set(1, 1, 0.5f); lights[1].power = 0.4f; //lights[1].kC = 1.f; //lights[1].kL = 0.01f; //lights[1].kQ = 0.001f; //lights[1].cosCutoff = cos(Math::DegreeToRadian(45)); //lights[1].cosInner = cos(Math::DegreeToRadian(30)); //lights[1].exponent = 3.f; //lights[1].spotDirection.Set(0.f, 1.f, 0.f); glUniform1i(m_parameters[U_NUMLIGHTS], 1); glUniform1i(m_parameters[U_TEXT_ENABLED], 0); glUniform1i(m_parameters[U_LIGHT0_TYPE], lights[0].type); glUniform3fv(m_parameters[U_LIGHT0_COLOR], 1, &lights[0].color.r); glUniform1f(m_parameters[U_LIGHT0_POWER], lights[0].power); glUniform1f(m_parameters[U_LIGHT0_KC], lights[0].kC); glUniform1f(m_parameters[U_LIGHT0_KL], lights[0].kL); glUniform1f(m_parameters[U_LIGHT0_KQ], lights[0].kQ); glUniform1f(m_parameters[U_LIGHT0_COSCUTOFF], lights[0].cosCutoff); glUniform1f(m_parameters[U_LIGHT0_COSINNER], lights[0].cosInner); glUniform1f(m_parameters[U_LIGHT0_EXPONENT], lights[0].exponent); glUniform1i(m_parameters[U_LIGHT1_TYPE], lights[1].type); glUniform3fv(m_parameters[U_LIGHT1_COLOR], 1, &lights[1].color.r); glUniform1f(m_parameters[U_LIGHT1_POWER], lights[1].power); glUniform1f(m_parameters[U_LIGHT1_KC], lights[1].kC); glUniform1f(m_parameters[U_LIGHT1_KL], lights[1].kL); glUniform1f(m_parameters[U_LIGHT1_KQ], lights[1].kQ); glUniform1f(m_parameters[U_LIGHT1_COSCUTOFF], lights[1].cosCutoff); glUniform1f(m_parameters[U_LIGHT1_COSINNER], lights[1].cosInner); glUniform1f(m_parameters[U_LIGHT1_EXPONENT], lights[1].exponent); camera.Init(Vector3(0, 0, 10), Vector3(0, 0, 0), Vector3(0, 1, 0)); for(int i = 0; i < NUM_GEOMETRY; ++i) { meshList[i] = NULL; } meshList[GEO_AXES] = MeshBuilder::GenerateAxes("reference", 1000, 1000, 1000); meshList[GEO_QUAD] = MeshBuilder::GenerateQuad("quad", Color(1, 1, 1), 1.f); meshList[GEO_QUAD]->textureID[0] = LoadTGA("Image//calibri.tga"); meshList[GEO_TEXT] = MeshBuilder::GenerateText("text", 16, 16); meshList[GEO_TEXT]->textureID[0] = LoadTGA("Image//calibri.tga"); meshList[GEO_TEXT]->material.kAmbient.Set(1, 0, 0); meshList[GEO_OBJECT] = MeshBuilder::GenerateOBJ("OBJ1", "OBJ//chair.obj");//MeshBuilder::GenerateCube("cube", 1); meshList[GEO_OBJECT]->textureID[0] = LoadTGA("Image//chair.tga"); meshList[GEO_RING] = MeshBuilder::GenerateRing("ring", Color(1, 0, 1), 36, 1, 0.5f); meshList[GEO_LIGHTBALL] = MeshBuilder::GenerateSphere("lightball", Color(1, 1, 1), 18, 36, 1.f); meshList[GEO_SPHERE] = MeshBuilder::GenerateSphere("sphere", Color(1, 0, 0), 18, 36, 10.f); //meshList[GEO_CUBE] = MeshBuilder::GenerateCube("cube", 1, 1, 1); //meshList[GEO_TORUS] = MeshBuilder::GenerateCylinder("torus", 36, 36, 5, 1); meshList[GEO_CONE] = MeshBuilder::GenerateCone("cone", Color(0.5f, 1, 0.3f), 36, 10.f, 10.f); meshList[GEO_CONE]->material.kDiffuse.Set(0.99f, 0.99f, 0.99f); meshList[GEO_CONE]->material.kSpecular.Set(0.f, 0.f, 0.f); meshList[GEO_LEFT] = MeshBuilder::GenerateQuad("LEFT", Color(1, 1, 1), 1.f); meshList[GEO_LEFT]->textureID[0] = LoadTGA("Image//left.tga"); meshList[GEO_RIGHT] = MeshBuilder::GenerateQuad("RIGHT", Color(1, 1, 1), 1.f); meshList[GEO_RIGHT]->textureID[0] = LoadTGA("Image//right.tga"); meshList[GEO_TOP] = MeshBuilder::GenerateQuad("TOP", Color(1, 1, 1), 1.f); meshList[GEO_TOP]->textureID[0] = LoadTGA("Image//top.tga"); meshList[GEO_BOTTOM] = MeshBuilder::GenerateQuad("BOTTOM", Color(1, 1, 1), 1.f); meshList[GEO_BOTTOM]->textureID[0] = LoadTGA("Image//bottom.tga"); meshList[GEO_FRONT] = MeshBuilder::GenerateQuad("FRONT", Color(1, 1, 1), 1.f); meshList[GEO_FRONT]->textureID[0] = LoadTGA("Image//front.tga"); meshList[GEO_BACK] = MeshBuilder::GenerateQuad("BACK", Color(1, 1, 1), 1.f); meshList[GEO_BACK]->textureID[0] = LoadTGA("Image//back.tga"); meshList[GEO_CROSSHAIR] = MeshBuilder::GenerateCrossHair("CRosshair", 0, 1, 1, 5); // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 1000 units Mtx44 perspective; perspective.SetToPerspective(45.0f, 4.0f / 3.0f, 0.1f, 10000.0f); //perspective.SetToOrtho(-80, 80, -60, 60, -1000, 1000); projectionStack.LoadMatrix(perspective); rotateAngle = 0; bLightEnabled = true; }
void ObjLoader::initOGLData() { // Seleccionamos los shaders que queremos cargar ShaderInfo shaders1[] = { { GL_VERTEX_SHADER, "../Shaders/Demo_OGL_MESH/texture.vs.glsl" }, { GL_FRAGMENT_SHADER, "../Shaders/Demo_OGL_MESH/texture.fs.glsl" }, { GL_NONE, NULL } }; render_prog = LoadShaders(shaders1); glUseProgram(render_prog); render_texture_loc = glGetUniformLocation(render_prog, "texture_diffuse"); glUniform1i(render_texture_loc, 0); //Texture unit 0 is for base images. render_model_matrix_loc = glGetUniformLocation(render_prog, "model_matrix"); render_projection_matrix_loc = glGetUniformLocation(render_prog, "projection_matrix"); Group group = groups.front(); // Pedimos un buffer para el element buffer object glGenBuffers(1, ebo); // Le hacemos hueco diciendole el tipo de buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo[0]); // Lo rellenamos con los indices de los cubos glBufferData(GL_ELEMENT_ARRAY_BUFFER, group.sizeOfFaces, group.faces, GL_STATIC_DRAW); // Pedimos un array de vertices glGenVertexArrays(1, vao); // Le hacemos hueco glBindVertexArray(vao[0]); // Pedimos un buffer para el vertex buffer object glGenBuffers(2, vbo); // Le hacemos hueco glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); // Le decimos que el hueco tiene que ser de tamaño "tamaño de cube positions"+"tamaño de cube colors" glBufferData(GL_ARRAY_BUFFER, group.sizeOfVertex + group.sizeOfTexCoords, NULL, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, group.sizeOfVertex, group.vertex); glBufferSubData(GL_ARRAY_BUFFER, group.sizeOfVertex, group.sizeOfTexCoords, group.texCoord); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glVertexAttribPointer(1, 2, GL_FLOAT, GL_TRUE, 0, (const GLvoid*)(group.sizeOfVertex)); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); texture_A_id = 0; // You should probably use CSurface::OnLoad ... ;) //-- and make sure the Surface pointer is good! texture_A = IMG_Load("../Resources/ObjTex/QuantumArid_Diffuse_A.jpg"); glActiveTexture(GL_TEXTURE0 + 0); glGenTextures(1, &texture_A_id); glBindTexture(GL_TEXTURE_2D, texture_A_id); glBindSampler(0, GL_LINEAR); int mode = GL_RGB; if (texture_A->format->BytesPerPixel == 4) mode = GL_RGBA; glTexImage2D(GL_TEXTURE_2D, 0, mode, texture_A->w, texture_A->h, 0, mode, GL_UNSIGNED_BYTE, texture_A->pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); }
/*!**************************************************************************** @Function InitView @Return bool true if no error occured @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES2StencilBuffer::InitView() { CPVRTString ErrorStr; /* Initialize VBO data */ m_Cylinder.LoadVbos(); m_Sphere.LoadVbos(); /* Load textures */ if (!LoadTextures(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } /* Load and compile the shaders & link programs */ if (!LoadShaders(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Set the sampler2D uniforms to corresponding texture units glUniform1i(glGetUniformLocation(m_ShaderProgram.uiId, "sTexture"), 0); // Is the screen rotated? bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); /* Initialize Print3D */ if(m_Print3D.SetTextures(0,PVRShellGet(prefWidth),PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } /* Set OpenGL ES render states needed for this training course */ // Enable backface culling and depth test glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // Use a nice bright blue as clear colour glClearColor(0.6f, 0.8f, 1.0f, 1.0f); // Set stencil clear value glClearStencil(0); return true; }
void Texture::load(float x, float y, float subWidth, float subHeight, float imageWidth, float imageHeight) { if(!shaderLoaded) { programID = LoadShaders(); shaderLoaded=true; } scale = 1; float topLeftS = x / imageWidth; float topLeftT = (y+subHeight) / imageHeight; float topRightS = (x + subWidth) / imageWidth; float topRightT = (y+subHeight) / imageHeight; float bottomRightS = (x + subWidth) / imageWidth; float bottomRightT = (y) / imageHeight; float bottomLeftS = x / imageWidth; float bottomLeftT = (y)/ imageHeight; //Center /*GLfloat quad_vertices[] = { -width/2.f, -height/2.f, //Bottom Left width/2.f, -height/2.f, //Bottom Right width/2.f, height/2.f, //Top Right -width/2.f, height/2.f,}; //Top Left*/ GLfloat quad_vertices[] = { 0.0f, subHeight, //Bottom Left subWidth, subHeight, //Bottom Right subWidth, 0.0f, //Top Right 0.0f, 0.0f,}; //Top Left glGenBuffers(1, &vbo_quad_vertices); glBindBuffer(GL_ARRAY_BUFFER, vbo_quad_vertices); glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), quad_vertices, GL_STATIC_DRAW); GLfloat quad_texcoords[] = { topLeftS, topLeftT, topRightS, topRightT, bottomRightS, bottomRightT, bottomLeftS, bottomLeftT, }; glGenBuffers(1, &vbo_quad_texcoords); glBindBuffer(GL_ARRAY_BUFFER, vbo_quad_texcoords); glBufferData(GL_ARRAY_BUFFER, sizeof(quad_texcoords), quad_texcoords, GL_STATIC_DRAW); GLushort quad_elements[] = {0, 1, 2, 2, 3, 0,}; glGenBuffers(1, &ibo_quad_elements); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_quad_elements); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quad_elements), quad_elements, GL_STATIC_DRAW); attribute_coord2d = glGetAttribLocation(programID, "coord2d"); attribute_texcoord = glGetAttribLocation(programID, "texcoord"); uniform_mvp = glGetUniformLocation(programID, "mvp"); uniform_mytexture = glGetUniformLocation(programID, "mytexture"); if(attribute_coord2d==-1 || attribute_texcoord==-1 || uniform_mvp==-1 || uniform_mytexture==-1) printf("Cound not bind attributes in texture"); }
void load_b(const char * objName, GLFWwindow * window){ GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders( "StandardShading.vertexshader", "StandardShading.fragmentshader" ); // Get a handle for our "MVP" uniform GLuint MatrixID = glGetUniformLocation(programID, "MVP"); GLuint ViewMatrixID = glGetUniformLocation(programID, "V"); GLuint ModelMatrixID = glGetUniformLocation(programID, "M"); // Load the texture // GLuint Texture = loadDDS("uvmap.DDS"); GLuint Texture = loadBMP_custom("hero.bmp"); // Get a handle for our "myTextureSampler" uniform GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler"); // Read our .obj file std::vector<glm::vec3> vertices,vertices2; std::vector<glm::vec2> uvs,uvs2; std::vector<glm::vec3> normals,normals2; bool res2 = loadOBJ(objName, vertices, uvs, normals); // Load it into a VBO GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); GLuint uvbuffer; glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW); GLuint normalbuffer; glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); // Get a handle for our "LightPosition" uniform glUseProgram(programID); GLuint LightID = glGetUniformLocation(programID, "LightPosition_worldspace"); do{ // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Use our shader glUseProgram(programID); // Compute the MVP matrix from keyboard and mouse input computeMatricesFromInputs(); glm::mat4 ProjectionMatrix = getProjectionMatrix2(); glm::mat4 ViewMatrix = getViewMatrix2(); // glm::mat4 ViewMatrix = glm::Rotate(ViewMatrix,5, glm::vec3(-1.0f, 0.0f, 0.0f)); glm::mat4 ModelMatrix = glm::mat4(1.0); glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); glm::vec3 lightPos = glm::vec3(4,2,4); glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(TextureID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer( 1, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Draw the triangles ! glDrawArrays(GL_TRIANGLES, 0, vertices.size() ); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS && glfwWindowShouldClose(window) == 0 ); // Cleanup VBO and shader glDeleteBuffers(1, &vertexbuffer); glDeleteBuffers(1, &uvbuffer); glDeleteBuffers(1, &normalbuffer); glDeleteProgram(programID); glDeleteTextures(1, &Texture); glDeleteVertexArrays(1, &VertexArrayID); }
void OpeningCutScene2::Init() { // Init VBO here // Set background color to dark blue glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //Enable depth buffer and depth testing glEnable(GL_DEPTH_TEST); //Enable back face culling glEnable(GL_CULL_FACE); //Default to fill mode glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Generate a default VAO for now glGenVertexArrays(1, &m_vertexArrayID); glBindVertexArray(m_vertexArrayID); m_programID = LoadShaders("Shader//Texture.vertexshader", "Shader//Text.fragmentshader"); m_parameters[U_MVP] = glGetUniformLocation(m_programID, "MVP"); m_parameters[U_MODELVIEW] = glGetUniformLocation(m_programID, "MV"); m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE] = glGetUniformLocation(m_programID, "MV_inverse_transpose"); m_parameters[U_MATERIAL_AMBIENT] = glGetUniformLocation(m_programID, "material.kAmbient"); m_parameters[U_MATERIAL_DIFFUSE] = glGetUniformLocation(m_programID, "material.kDiffuse"); m_parameters[U_MATERIAL_SPECULAR] = glGetUniformLocation(m_programID, "material.kSpecular"); m_parameters[U_MATERIAL_SHININESS] = glGetUniformLocation(m_programID, "material.kShininess"); m_parameters[U_LIGHT0_POSITION] = glGetUniformLocation(m_programID, "lights[0].position_cameraspace"); m_parameters[U_LIGHT0_COLOR] = glGetUniformLocation(m_programID, "lights[0].color"); m_parameters[U_LIGHT0_POWER] = glGetUniformLocation(m_programID, "lights[0].power"); m_parameters[U_LIGHT0_KC] = glGetUniformLocation(m_programID, "lights[0].kC"); m_parameters[U_LIGHT0_KL] = glGetUniformLocation(m_programID, "lights[0].kL"); m_parameters[U_LIGHT0_KQ] = glGetUniformLocation(m_programID, "lights[0].kQ"); m_parameters[U_LIGHT0_TYPE] = glGetUniformLocation(m_programID, "lights[0].type"); m_parameters[U_LIGHT0_SPOTDIRECTION] = glGetUniformLocation(m_programID, "lights[0].spotDirection"); m_parameters[U_LIGHT0_COSCUTOFF] = glGetUniformLocation(m_programID, "lights[0].cosCutoff"); m_parameters[U_LIGHT0_COSINNER] = glGetUniformLocation(m_programID, "lights[0].cosInner"); m_parameters[U_LIGHT0_EXPONENT] = glGetUniformLocation(m_programID, "lights[0].exponent"); m_parameters[U_LIGHTENABLED] = glGetUniformLocation(m_programID, "lightEnabled"); m_parameters[U_NUMLIGHTS] = glGetUniformLocation(m_programID, "numLights"); m_parameters[U_COLOR_TEXTURE_ENABLED] = glGetUniformLocation(m_programID, "colorTextureEnabled"); m_parameters[U_COLOR_TEXTURE] = glGetUniformLocation(m_programID, "colorTexture"); m_parameters[U_TEXT_ENABLED] = glGetUniformLocation(m_programID, "textEnabled"); m_parameters[U_TEXT_COLOR] = glGetUniformLocation(m_programID, "textColor"); glUseProgram(m_programID); light[0].type = Light::LIGHT_SPOT; light[0].position.Set(camera.position.x, camera.position.y, camera.position.z); light[0].color.Set(1, 1, 1); light[0].power = 2.0f; light[0].kC = 1.f; light[0].kL = 0.01f; light[0].kQ = 0.001f; light[0].cosCutoff = cos(Math::DegreeToRadian(30)); light[0].cosInner = cos(Math::DegreeToRadian(15)); light[0].exponent = 3.f; light[0].spotDirection.Set(-(camera.target.x - camera.position.x), -(camera.target.y - camera.position.y), -(camera.target.z - camera.position.z)); // Pass information glUniform1i(m_parameters[U_NUMLIGHTS], 1); glUniform1i(m_parameters[U_LIGHT0_TYPE], light[0].type); glUniform3fv(m_parameters[U_LIGHT0_COLOR], 1, &light[0].color.r); glUniform1f(m_parameters[U_LIGHT0_POWER], light[0].power); glUniform1f(m_parameters[U_LIGHT0_KC], light[0].kC); glUniform1f(m_parameters[U_LIGHT0_KL], light[0].kL); glUniform1f(m_parameters[U_LIGHT0_KQ], light[0].kQ); glUniform1f(m_parameters[U_LIGHT0_COSCUTOFF], light[0].cosCutoff); glUniform1f(m_parameters[U_LIGHT0_COSINNER], light[0].cosInner); glUniform1f(m_parameters[U_LIGHT0_EXPONENT], light[0].exponent); //Initialize camera settings camera.Init(Vector3(0, 10, 0), Vector3(0, 15, 1), Vector3(0, 1, 0)); meshList[GEO_AXES] = MeshBuilder::GenerateAxes("reference", 1000, 1000, 1000); meshList[GEO_LIGHTBALL] = MeshBuilder::GenerateSphere("lightball", Color(1, 1, 1), 10, 20); meshList[GEO_FRONT] = MeshBuilder::GenerateQuad("front", Color(1, 1, 1)); meshList[GEO_FRONT]->textureID = LoadTGA("Image//SkyBox1_front.tga"); meshList[GEO_LEFT] = MeshBuilder::GenerateQuad("left", Color(1, 1, 1)); meshList[GEO_LEFT]->textureID = LoadTGA("Image//SkyBox1_left.tga"); meshList[GEO_RIGHT] = MeshBuilder::GenerateQuad("right", Color(1, 1, 1)); meshList[GEO_RIGHT]->textureID = LoadTGA("Image//SkyBox1_right.tga"); meshList[GEO_TOP] = MeshBuilder::GenerateQuad("top", Color(1, 1, 1)); meshList[GEO_TOP]->textureID = LoadTGA("Image//SkyBox1_up.tga"); meshList[GEO_BOTTOM] = MeshBuilder::GenerateQuad("SkyBox1_down", Color(1, 1, 1)); meshList[GEO_BOTTOM]->textureID = LoadTGA("Image//SkyBox1_down.tga"); meshList[GEO_BACK] = MeshBuilder::GenerateQuad("SkyBox1_back", Color(1, 1, 1)); meshList[GEO_BACK]->textureID = LoadTGA("Image//SkyBox1_back.tga"); meshList[GEO_QUAD] = MeshBuilder::GenerateQuad("SceneOpening", Color(0, 0, 0)); meshList[GEO_TEXT] = MeshBuilder::GenerateText("text", 16, 16); meshList[GEO_TEXT]->textureID = LoadTGA("Image//calibri.tga"); meshList[GEO_PLANETFLOOR] = MeshBuilder::GenerateQuad("planet floor", Color(1, 1, 1)); meshList[GEO_PLANETFLOOR]->textureID = LoadTGA("Image//PlanetFloor.tga"); meshList[GEO_FACILITYOUT] = MeshBuilder::GenerateOBJ("Facility Outer", "OBJ//FacilityOUT.obj"); meshList[GEO_FACILITYOUT]->textureID = LoadTGA("Image//FacilityOUT.tga"); meshList[GEO_FACILITYOUTWALL] = MeshBuilder::GenerateQuad("FacilityOUT wall", Color(1, 1, 1)); meshList[GEO_FACILITYOUTWALL]->textureID = LoadTGA("Image//OutsideWALL.tga"); meshList[GEO_DEADBODY] = MeshBuilder::GenerateOBJ("Pile of dead body", "OBJ//DeadBody.obj"); meshList[GEO_DEADBODY]->textureID = LoadTGA("Image//DeadBody.tga"); Mtx44 projection; projection.SetToPerspective(45.f, 16.f / 9.f, 0.1f, 10000.f); projectionStack.LoadMatrix(projection); rotateCamX = false; MoveCamera1 = 0; camera_check1 = true; camera_check2 = false; camera_check3 = false; rotateCamY = false; RotateCamera = 0; wokeUp = true; check1 = true; check2 = false; check3 = false; eyeOpening = 0; text1 = false; text2 = false; // All Switches Debounce Key }
int main(void) { GLFWwindow* window; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); window = glfwCreateWindow(1024, 768, "Simple example", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); // Initialize GLEW glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders( "../resources/shaders/SimpleVertexShader.vertexshader", "../resources/shaders/SimpleFragmentShader.fragmentshader" ); initGL(); Tunnel *myTunnel = new Tunnel(vec3(0.0f,0.0f,1.0f), 2, 1.0f, 1.0f); Tunnel myTunnel2 = Tunnel(vec3(0.0f,0.0f,-3.0f), 2, 1.0f, 1.0f); for (int i=0; i<10; i++){ Cube3d *myCube = new Cube3d(0.5f, vec3(0.0f,0.0f,(GLfloat) -i)); myCubeVect.push_back(myCube); } //Cube3d *myCube = new Cube3d(0.5f); while (!glfwWindowShouldClose(window)) { playerPos = (int) camPosZ; int index = playerPos; if(index>10){ int div = (int) playerPos/10; index = playerPos - div*10; } // printf("playerPos=%d; index=%d\n", playerPos, index); if (index>0) { myCubeVect[index-1]->setTranslation(vec3(0.0f,0.0f,-10.0f)); } //myCube2->setTranslation(vec3(0.0f,0.0f,-playerPos)); /* Clear The Screen And The Depth Buffer */ glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); float ratio; int width, height; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); // glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); /* Set our perspective */ gluPerspective( 45.0f, ratio, 0.1f, 500.0f ); //glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f); //gluOrtho2D( 0,width,0,height ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadIdentity(); glRotatef(camRotY, 0.0f, 1.0f, 0.0f); //glTranslatef(0, 0, 5); glTranslatef(camPosX, camPosY, camPosZ); //>>>>>>>>>>>>>>>>>>START drawing our level<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /*for(int i=0; i<myCubeVect.size(); ++i) { myCubeVect[i]->draw(); }*/ myTunnel->draw(); myTunnel2.draw(); /*glBegin(GL_LINES); glVertex3f(0.0f, 1.0f, 0.0f); glVertex3f(sinf(pi/4), cosf(pi/4),0.0f); glVertex3f(sinf(pi/4), cosf(pi/4),0.0f); glVertex3f(sinf(pi/2), cosf(pi/2),0.0f); glVertex3f(sinf(pi/2), cosf(pi/2),0.0f); glVertex3f(sinf(3*pi/4), cosf(3*pi/4),0.0f); glVertex3f(sinf(3*pi/4), cosf(3*pi/4),0.0f); glVertex3f(sinf(pi), cosf(pi),0.0f); glEnd();*/ rotTri+=3.0f; glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
void Render() { GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); GLuint programID = LoadShaders("vertex.glsl", "fragment.glsl"); GLfloat g_vertex_buffer_data[max_n][2]; GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); float central_angle = 2 * PI / N; // float step_d = step / sin((PI - central_angle) / 2) * sin(central_angle); float step_d = step; glm::vec2 direction = glm::normalize(glm::vec2(step_d, 0)); glm::vec2 direction_d = glm::rotate(glm::vec2(0, -1), float(-360.0 / N / 2)); // glm::vec2 position = direction_d * step; glm::vec2 position = glm::vec2(0, 0); int n = 0; float ratio = 0; do { glClear(GL_COLOR_BUFFER_BIT); glUseProgram(programID); step_d = step; direction = glm::normalize(glm::vec2(step_d, 0)); position = glm::vec2(0, 0); g_vertex_buffer_data[0][0] = position.x * window_ratio; g_vertex_buffer_data[0][1] = position.y; for(int j = 0; j < 1000; j++) { for(int i = 1; i <= N; i++) { position += direction * step_d * (i == n ? ratio : 1); g_vertex_buffer_data[j * 10 + i][0] = position.x * window_ratio; g_vertex_buffer_data[j * 10 + i][1] = position.y; direction = glm::rotate(direction, float(360.0 / N * 2)); // step_d *= 0.95; } step_d *= 0.99; direction = glm::rotate(direction, float(360.0 / 36)); } n = 1000 * N; glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, (n + 1) * sizeof(GLfloat) * 2, g_vertex_buffer_data, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // The attribute we want to configure 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glDrawArrays(GL_LINE_STRIP, 0, n + 1); glDisableVertexAttribArray(0); glfwSwapBuffers(window); glfwPollEvents(); usleep(500); ratio += 0.01; if(ratio >= 1) n++, ratio = 0; } while(glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && !glfwWindowShouldClose(window)); glDeleteBuffers(1, &vertexbuffer); glDeleteVertexArrays(1, &VertexArrayID); glDeleteProgram(programID); }
/*!**************************************************************************** @Function InitView @Return bool true if no error occurred @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES2FilmTV::InitView() { CPVRTString ErrorStr; // Initialize VBO data if(!LoadVbos(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Load textures if(!LoadTextures(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Load and compile the shaders & link programs if(!LoadShaders(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Initialize Print3D bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); if(m_Print3D.SetTextures(0,PVRShellGet(prefWidth),PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } //Set OpenGL ES render states needed for this demo // Enable backface culling and depth test glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Find the largest square power of two texture that fits into the viewport m_i32TexSize = 1; int iSize = PVRT_MIN(PVRShellGet(prefWidth), PVRShellGet(prefHeight)); while (m_i32TexSize * 2 < iSize) m_i32TexSize *= 2; // Get the currently bound frame buffer object. On most platforms this just gives 0. glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_i32OriginalFB); for(int i = 0; i < 2; ++i) { // Create texture for the FBO glGenTextures(1, &m_uiTexture[i]); glBindTexture(GL_TEXTURE_2D, m_uiTexture[i]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_i32TexSize, m_i32TexSize, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 0); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Create FBO glGenFramebuffers(1, &m_uiFbo[i]); glBindFramebuffer(GL_FRAMEBUFFER, m_uiFbo[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_uiTexture[i], 0); glGenRenderbuffers(1, &m_uiDepthBuffer[i]); glBindRenderbuffer(GL_RENDERBUFFER, m_uiDepthBuffer[i]); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, m_i32TexSize, m_i32TexSize); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_uiDepthBuffer[i]); // Check that our FBO creation was successful GLuint uStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(uStatus != GL_FRAMEBUFFER_COMPLETE) { m_bFBOsCreated = false; PVRShellOutputDebug("ERROR: Failed to initialise FBO"); break; } // Clear the colour buffer for this FBO glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } glBindFramebuffer(GL_FRAMEBUFFER, m_i32OriginalFB); // Setup the main camera PVRTVec3 vFrom, vTo(0.0f), vUp(0.0f, 1.0f, 0.0f); float fFOV; // Camera nodes are after the mesh and light nodes in the array int i32CamID = m_Scene.pNode[m_Scene.nNumMeshNode + m_Scene.nNumLight + g_ui32Camera].nIdx; // Get the camera position, target and field of view (fov) if(m_Scene.pCamera[i32CamID].nIdxTarget != -1) // Does the camera have a target? fFOV = m_Scene.GetCameraPos( vFrom, vTo, g_ui32Camera); // vTo is taken from the target node else fFOV = m_Scene.GetCamera( vFrom, vTo, vUp, g_ui32Camera); // vTo is calculated from the rotation m_View = PVRTMat4::LookAtRH(vFrom, vTo, vUp); // Calculate the projection matrix PVRTMat4 mProjection = PVRTMat4::PerspectiveFovRH(fFOV, (float)PVRShellGet(prefWidth)/(float)PVRShellGet(prefHeight), g_fCameraNear, g_fCameraFar, PVRTMat4::OGL, bRotate); m_ViewProjection = mProjection * m_View; // Check to see if the GL_EXT_discard_framebuffer extension is supported if(m_bFBOsCreated && (m_bDiscard = CPVRTgles2Ext::IsGLExtensionSupported("GL_EXT_discard_framebuffer")) != false) { m_Extensions.LoadExtensions(); m_bDiscard = m_Extensions.glDiscardFramebufferEXT != 0; } return true; }
/*!**************************************************************************** @Function InitView @Return bool true if no error occured @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES2AnisotropicLighting::InitView() { CPVRTString ErrorStr; /* Initialize VBO data */ LoadVbos(); /* Load textures */ if (!LoadTextures(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } /* Load and compile the shaders & link programs */ if (!LoadShaders(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Is the screen rotated? bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); /* Initialize Print3D */ if(m_Print3D.SetTextures(0,PVRShellGet(prefWidth),PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } /* Calculate the projection and view matrices */ float fAspect = PVRShellGet(prefWidth) / (float)PVRShellGet(prefHeight); m_mViewProj = PVRTMat4::PerspectiveFovFloatDepthRH(CAM_FOV, fAspect, CAM_NEAR, PVRTMat4::OGL, bRotate); m_mViewProj *= PVRTMat4::LookAtRH(PVRTVec3(0.f, 0.f, 150.f), PVRTVec3(0.f), PVRTVec3(0.f, 1.f, 0.f)); /* Set uniforms that are constant throughout this training course */ // Set the sampler2D variable to the first texture unit glUseProgram(m_FastShader.uiId); glUniform1i(glGetUniformLocation(m_FastShader.uiId, "sTexture"), 0); // Define material properties glUseProgram(m_SlowShader.uiId); float afMaterial[4] = { 0.4f, // Diffuse intensity scale 0.6f, // Diffuse intensity bias 0.82f, // Specular intensity scale 0.0f, // Specular bias }; glUniform4fv(glGetUniformLocation(m_SlowShader.uiId, "Material"), 1, afMaterial); // Set surface grain direction PVRTVec3 vMsGrainDir = PVRTVec3(2, 1, 0).normalized(); glUniform3fv(glGetUniformLocation(m_SlowShader.uiId, "GrainDir"), 1, vMsGrainDir.ptr()); /* Set OpenGL ES render states needed for this training course */ // Enable backface culling and depth test glCullFace(GL_BACK); glEnable(GL_CULL_FACE); // Enable z-buffer test // We are using a projection matrix optimized for a floating point depth buffer, // so the depth test and clear value need to be inverted (1 becomes near, 0 becomes far). glEnable(GL_DEPTH_TEST); glDepthFunc(GL_GEQUAL); glClearDepthf(0.0f); // Use a nice bright blue as clear colour glClearColor(0.6f, 0.8f, 1.0f, 1.0f); m_fAngleY = 0; m_eRenderMode = eTexLookup; return true; }
/*!**************************************************************************** @Function InitView @Return bool true if no error occured @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES2Bumpmap::InitView() { CPVRTString ErrorStr; /* Initialize VBO data */ LoadVbos(); /* Load textures */ if (!LoadTextures(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } /* Load and compile the shaders & link programs */ if (!LoadShaders(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Set the sampler2D uniforms to corresponding texture units glUniform1i(glGetUniformLocation(m_ShaderProgram.uiId, "sBaseTex"), 0); glUniform1i(glGetUniformLocation(m_ShaderProgram.uiId, "sNormalMap"), 1); // Is the screen rotated bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); /* Initialize Print3D */ if(m_Print3D.SetTextures(0,PVRShellGet(prefWidth),PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } /* Calculate the projection and view matrices */ float fAspect = PVRShellGet(prefWidth) / (float)PVRShellGet(prefHeight); m_mViewProj = PVRTMat4::PerspectiveFovFloatDepthRH(CAM_FOV, fAspect, CAM_NEAR, PVRTMat4::OGL, bRotate); m_mViewProj *= PVRTMat4::LookAtRH(PVRTVec3(0, 0, 150), PVRTVec3(0, 0, 0), PVRTVec3(0, 1, 0)); /* Set OpenGL ES render states needed for this training course */ // Enable backface culling and depth test glCullFace(GL_BACK); glEnable(GL_CULL_FACE); // Enable z-buffer test // We are using a projection matrix optimized for a floating point depth buffer, // so the depth test and clear value need to be inverted (1 becomes near, 0 becomes far). glEnable(GL_DEPTH_TEST); glDepthFunc(GL_GEQUAL); glClearDepthf(0.0f); // Use a nice bright blue as clear colour glClearColor(0.6f, 0.8f, 1.0f, 1.0f); return true; }
void Ex08_13::InitGL() { if (! LoadGL() ) return; ShaderInfo object_shaders[] = { { GL_VERTEX_SHADER, "Shaders/sh08_13.vert" }, { GL_FRAGMENT_SHADER, "Shaders/sh08_13.frag" }, { GL_NONE, NULL } }; object_prog = LoadShaders( object_shaders ); glGenBuffers(1, &quad_vbo); glBindBuffer(GL_ARRAY_BUFFER, quad_vbo); static const GLfloat quad_data[] = { 0.75f, -0.75f, -0.75f, -0.75f, -0.75f, 0.75f, 0.75f, 0.75f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; glBufferData(GL_ARRAY_BUFFER, sizeof(quad_data), quad_data, GL_STATIC_DRAW); glGenVertexArrays(1, &vao); glBindVertexArray(vao); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(8 * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET((8 + 8) * sizeof(float))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glLinkProgram(object_prog); object_mat_mv_loc = glGetUniformLocation(object_prog, "MVMatrix"); object_mat_mvp_loc = glGetUniformLocation(object_prog, "MVPMatrix"); GLuint NormalMatrix_loc = glGetUniformLocation(object_prog, "NormalMatrix"); GLuint LightPosition_loc = glGetUniformLocation(object_prog, "LightPosition"); GLuint Color0_loc = glGetUniformLocation(object_prog, "Color0"); GLuint Color1_loc = glGetUniformLocation(object_prog, "Color1"); GLuint AvgColor_loc = glGetUniformLocation(object_prog, "AvgColor"); GLuint Frequency_loc = glGetUniformLocation(object_prog, "Frequency"); glUseProgram(object_prog); GLfloat normal_matrix[3 * 3] = { 0.5f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f }; glUniformMatrix3fv(NormalMatrix_loc, 1, GL_TRUE, normal_matrix); glUniform3fv(LightPosition_loc, 1, vmath::vec3(0.0f, 0.0f, -1.0f)); glUniform3fv(Color0_loc, 1, vmath::vec3(0.0f, 0.0f, 0.7f)); glUniform3fv(Color1_loc, 1, vmath::vec3(1.0f, 1.0f, 0.0f)); glUniform3fv(AvgColor_loc, 1, vmath::vec3(1.0f, 1.0f, 1.0f)); glUniform1f(Frequency_loc, 3.0f); }
bool Scene::Init(HWND _hWnd) { hWnd = _hWnd; d3d9 = Direct3DCreate9( D3D_SDK_VERSION ); if (!d3d9) { return false; } D3DPRESENT_PARAMETERS presentParams; ZeroMemory( &presentParams, sizeof( presentParams ) ); presentParams.Windowed = TRUE; presentParams.SwapEffect = D3DSWAPEFFECT_DISCARD; presentParams.BackBufferFormat = D3DFMT_UNKNOWN; //D3DFMT_X8R8G8B8; presentParams.EnableAutoDepthStencil = TRUE; presentParams.AutoDepthStencilFormat = D3DFMT_D24S8; presentParams.PresentationInterval = D3DPRESENT_INTERVAL_ONE; presentParams.BackBufferCount = 1; presentParams.MultiSampleType = D3DMULTISAMPLE_8_SAMPLES; presentParams.MultiSampleQuality = 1; d3d9->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &presentParams, &device ); if (!device) { presentParams.MultiSampleType = D3DMULTISAMPLE_NONE; presentParams.MultiSampleQuality = 0; d3d9->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &presentParams, &device ); } if (!device) { Cleanup(); return false; } const D3DVERTEXELEMENT9 decl[] = { { 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, D3DDECL_END() }; device->CreateVertexDeclaration( decl, &vertexDecl ); if (!vertexDecl) { Cleanup(); return false; } if (!CreateQuad()) { Cleanup(); return false; } D3DXCreateTextureFromFileEx(device, L"InitialState.dds", D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, D3DX_FROM_FILE, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, &initialState); if (!initialState) { Cleanup(); return false; } D3DSURFACE_DESC textureDesc; initialState->GetLevelDesc(0, &textureDesc); device->CreateTexture(textureDesc.Width, textureDesc.Height, 1, D3DUSAGE_RENDERTARGET, textureDesc.Format, D3DPOOL_DEFAULT, &state0, NULL); if (!state0) { Cleanup(); return false; } device->CreateTexture(textureDesc.Width, textureDesc.Height, 1, D3DUSAGE_RENDERTARGET, textureDesc.Format, D3DPOOL_DEFAULT, &state1, NULL); if (!state1) { Cleanup(); return false; } device->GetRenderTarget(0, &rtMain); if (!rtMain) { Cleanup(); return false; } state0->GetSurfaceLevel(0, &rtState0); if (!rtState0) { Cleanup(); return false; } state1->GetSurfaceLevel(0, &rtState1); if (!rtState1) { Cleanup(); return false; } LoadShaders(); Reset(); return true; }
int main(int arc, char **argv) { // Initialize SDL if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { logSDLError(std::cout, "SDL_Init"); return 1; } // Create a window SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); if (win == nullptr) { logSDLError(std::cout, "SDL_CreateWindow"); return 2; } if (FULLSCREEN) { SDL_SetWindowFullscreen(win, SDL_WINDOW_FULLSCREEN_DESKTOP); } // Initialize and set up OpenGL SDL_GLContext sdl_opengl_context = SDL_GL_CreateContext(win); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 4); SDL_GL_SetSwapInterval(1); // Initialize GLEW if (glewInit() != GLEW_OK) { logGLEWError(std::cout, "glewInit"); return 3; } GLuint programID = LoadShaders("../gl_rift/src/VertexShader.glsl", "../gl_rift/src/FragmentShader.glsl"); glUseProgram(programID); //startup(); // Rendering loop int rendering = 1; while (rendering) { draw_stereo(programID); //render(SDL_GetTicks() /100); SDL_GL_SwapWindow(win); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: rendering = 0; case SDL_KEYDOWN: break; case SDL_KEYUP: if (event.key.keysym.sym == SDLK_ESCAPE) { rendering = 0; } break; } } } glDeleteProgram(programID); SDL_GL_DeleteContext(sdl_opengl_context); SDL_DestroyWindow(win); SDL_Quit(); return 0; }
/** ** Handle interactive input event. ** ** @param callbacks Callback structure for events. ** @param event SDL event structure pointer. */ static void SdlDoEvent(const EventCallback &callbacks, SDL_Event &event) { #if (defined(USE_OPENGL) || defined(USE_GLES)) // Scale mouse-coordinates to viewport if (ZoomNoResize && (event.type & (SDL_MOUSEBUTTONUP | SDL_MOUSEBUTTONDOWN | SDL_MOUSEMOTION))) { event.button.x = (Uint16)floorf(event.button.x * float(Video.Width) / Video.ViewportWidth); event.button.y = (Uint16)floorf(event.button.y * float(Video.Height) / Video.ViewportHeight); } #endif switch (event.type) { case SDL_MOUSEBUTTONDOWN: InputMouseButtonPress(callbacks, SDL_GetTicks(), event.button.button); break; case SDL_MOUSEBUTTONUP: InputMouseButtonRelease(callbacks, SDL_GetTicks(), event.button.button); break; // FIXME: check if this is only useful for the cursor // FIXME: if this is the case we don't need this. case SDL_MOUSEMOTION: InputMouseMove(callbacks, SDL_GetTicks(), event.motion.x, event.motion.y); // FIXME: Same bug fix from X11 if ((UI.MouseWarpPos.x != -1 || UI.MouseWarpPos.y != -1) && (event.motion.x != UI.MouseWarpPos.x || event.motion.y != UI.MouseWarpPos.y)) { int xw = UI.MouseWarpPos.x; int yw = UI.MouseWarpPos.y; UI.MouseWarpPos.x = -1; UI.MouseWarpPos.y = -1; SDL_WarpMouse(xw, yw); } break; case SDL_ACTIVEEVENT: if (event.active.state & SDL_APPMOUSEFOCUS) { static bool InMainWindow = true; if (InMainWindow && !event.active.gain) { InputMouseExit(callbacks, SDL_GetTicks()); } InMainWindow = (event.active.gain != 0); } if (!IsNetworkGame() && Preference.PauseOnLeave && (event.active.state & SDL_APPACTIVE || SDL_GetAppState() & SDL_APPACTIVE)) { static bool DoTogglePause = false; if (IsSDLWindowVisible && !event.active.gain) { IsSDLWindowVisible = false; if (!GamePaused) { DoTogglePause = true; UiTogglePause(); } } else if (!IsSDLWindowVisible && event.active.gain) { IsSDLWindowVisible = true; if (GamePaused && DoTogglePause) { DoTogglePause = false; UiTogglePause(); } } } break; case SDL_KEYDOWN: if (GLShaderPipelineSupported && event.key.keysym.sym == SDLK_SLASH && event.key.keysym.mod & KMOD_ALT && event.key.keysym.mod & KMOD_CTRL) { LoadShaders(); break; } InputKeyButtonPress(callbacks, SDL_GetTicks(), event.key.keysym.sym, event.key.keysym.unicode); break; case SDL_KEYUP: InputKeyButtonRelease(callbacks, SDL_GetTicks(), event.key.keysym.sym, event.key.keysym.unicode); break; case SDL_QUIT: Exit(0); break; } if (&callbacks == GetCallbacks()) { handleInput(&event); } }
void CSceneManager2D::Init() { // Blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Switch on culling glEnable(GL_CULL_FACE); // Render mode glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Activate blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Generate and bind vertex array glGenVertexArrays(1, &m_vertexArrayID); glBindVertexArray(m_vertexArrayID); // Load the shaders m_programID = LoadShaders( "Shader//Texture.vertexshader", "Shader//Text.fragmentshader" ); // Get a handle for our uniform m_parameters[U_MVP] = glGetUniformLocation(m_programID, "MVP"); //m_parameters[U_MODEL] = glGetUniformLocation(m_programID, "M"); //m_parameters[U_VIEW] = glGetUniformLocation(m_programID, "V"); m_parameters[U_MODELVIEW] = glGetUniformLocation(m_programID, "MV"); m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE] = glGetUniformLocation(m_programID, "MV_inverse_transpose"); // Get a handle for our "colorTexture" uniform m_parameters[U_COLOR_TEXTURE_ENABLED] = glGetUniformLocation(m_programID, "colorTextureEnabled"); m_parameters[U_COLOR_TEXTURE] = glGetUniformLocation(m_programID, "colorTexture"); // Get a handle for our "textColor" uniform m_parameters[U_TEXT_ENABLED] = glGetUniformLocation(m_programID, "textEnabled"); m_parameters[U_TEXT_COLOR] = glGetUniformLocation(m_programID, "textColor"); // Use our shader glUseProgram(m_programID); glUniform1i(m_parameters[U_TEXT_ENABLED], 0); // Initialise the camera camera.Init(Vector3(0, 0, 10), Vector3(0, 0, 0), Vector3(0, 1, 0)); // Create the meshes for(int i = 0; i < NUM_GEOMETRY; ++i) { meshList[i] = NULL; } meshList[GEO_TEXT] = MeshBuilder::GenerateText("text", 16, 16); meshList[GEO_TEXT]->textureID = LoadTGA("Image//calibri.tga"); meshList[GEO_TEXT]->material.kAmbient.Set(1, 0, 0); // Load the ground mesh and texture meshList[GEO_BACKGROUND] = MeshBuilder::Generate2DMesh("GEO_BACKGROUND", Color(1, 1, 1), 0, 0, 800, 600); meshList[GEO_BACKGROUND]->textureID = LoadTGA("Image//sky_background.tga"); meshList[GEO_TILEGROUND] = MeshBuilder::Generate2DMesh("GEO_TILEGROUND", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILEGROUND]->textureID = LoadTGA("Image//tile1_ground.tga"); meshList[GEO_TILEHERO] = MeshBuilder::Generate2DMesh("GEO_TILEHERO", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILEHERO]->textureID = LoadTGA("Image//tile2_hero.tga"); meshList[GEO_TILETREE] = MeshBuilder::Generate2DMesh("GEO_TILETREE", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILETREE]->textureID = LoadTGA("Image//tile3_tree.tga"); meshList[GEO_TILESTRUCTURE] = MeshBuilder::Generate2DMesh("GEO_TILESTRUCTURE", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILESTRUCTURE]->textureID = LoadTGA("Image//tile3_structure.tga"); meshList[GEO_TILEHERO_FRAME0] = MeshBuilder::Generate2DMesh("GEO_TILEHERO_FRAME0", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILEHERO_FRAME0]->textureID = LoadTGA("Image//tile2_hero_frame_0.tga"); meshList[GEO_TILEHERO_FRAME1] = MeshBuilder::Generate2DMesh("GEO_TILEHERO_FRAME1", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILEHERO_FRAME1]->textureID = LoadTGA("Image//tile2_hero_frame_1.tga"); meshList[GEO_TILEHERO_FRAME2] = MeshBuilder::Generate2DMesh("GEO_TILEHERO_FRAME2", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILEHERO_FRAME2]->textureID = LoadTGA("Image//tile2_hero_frame_2.tga"); meshList[GEO_TILEHERO_FRAME3] = MeshBuilder::Generate2DMesh("GEO_TILEHERO_FRAME3", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILEHERO_FRAME3]->textureID = LoadTGA("Image//tile2_hero_frame_3.tga"); meshList[GEO_TILE_KILLZONE] = MeshBuilder::Generate2DMesh("GEO_TILE_KILLZONE", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILE_KILLZONE]->textureID = LoadTGA("Image//tile10_killzone.tga"); meshList[GEO_TILE_SAFEZONE] = MeshBuilder::Generate2DMesh("GEO_TILE_SAFEZONE", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILE_SAFEZONE]->textureID = LoadTGA("Image//tile11_safezone.tga"); meshList[GEO_TILEENEMY_FRAME0] = MeshBuilder::Generate2DMesh("GEO_TILEENEMY_FRAME0", Color(1, 1, 1), 0, 0, 25, 25); meshList[GEO_TILEENEMY_FRAME0]->textureID = LoadTGA("Image//tile20_enemy.tga"); meshList[GEO_MENU] = MeshBuilder::Generate2DMesh("GEO_MENU", Color(1, 1, 1), 0, 0, 800, 600); meshList[GEO_MENU]->textureID = LoadTGA("Image//MainMenu.tga"); meshList[GEO_HIGHSCORE] = MeshBuilder::Generate2DMesh("GEO_HIGHSCORE", Color(1, 1, 1), 0, 0, 800, 600); meshList[GEO_HIGHSCORE]->textureID = LoadTGA("Image//Highscore.tga"); meshList[GEO_OPTION1] = MeshBuilder::Generate2DMesh("GEO_OPTION1", Color(1, 1, 1), 0, 0, 800, 600); meshList[GEO_OPTION1]->textureID = LoadTGA("Image//OptionsSoundOn.tga"); meshList[GEO_INSTRUCTION] = MeshBuilder::Generate2DMesh("GEO_INSTRUCTIONS", Color(1, 1, 1), 0, 0, 800, 600); meshList[GEO_INSTRUCTION]->textureID = LoadTGA("Image//Instructions.tga"); meshList[GEO_SELECT] = MeshBuilder::Generate2DMesh("GEO_SELECT", Color(1, 1, 1), 0, 0, 75, 55); meshList[GEO_SELECT]->textureID = LoadTGA("Image//Select.tga"); meshList[GEO_SPRITE_ANIMATION] = MeshBuilder::GenerateSpriteAnimation("cat", 1, 6); meshList[GEO_SPRITE_ANIMATION]->textureID = LoadTGA("Image//cat.tga"); m_spriteAnimation = dynamic_cast<SpriteAnimation*>(meshList[GEO_SPRITE_ANIMATION]); if (m_spriteAnimation) { m_spriteAnimation->m_anim = new Animation(); m_spriteAnimation->m_anim->Set(0, 5, 0, 0.1f); } /* // Initialise and load the tile map m_cMap = new CMap(); m_cMap->Init( 600, 800, 24, 32, 600, 1600 ); m_cMap->LoadMap( "Image//MapDesign.csv" ); // Initialise and load the REAR tile map m_cRearMap = new CMap(); m_cRearMap->Init( 600, 800, 24, 32, 600, 1600 ); m_cRearMap->LoadMap( "Image//MapDesign_Rear.csv" ); // Initialise the hero's position theHero = new CPlayerInfo(); theHero->SetPos_x(50); theHero->SetPos_y(100); // Load the texture for minimap m_cMinimap = new CMinimap(); m_cMinimap->SetBackground(MeshBuilder::GenerateMinimap("MINIMAP", Color(1, 1, 1), 1.f)); m_cMinimap->GetBackground()->textureID = LoadTGA("Image//grass_darkgreen.tga"); m_cMinimap->SetBorder( MeshBuilder::GenerateMinimapBorder("MINIMAPBORDER", Color(1, 1, 0), 1.f) ); m_cMinimap->SetAvatar( MeshBuilder::GenerateMinimapAvatar("MINIMAPAVATAR", Color(1, 1, 0), 1.f) ); // Set the strategy for the enemy theEnemy = new CEnemy(); theEnemy->ChangeStrategy( NULL, false); theEnemy->SetPos_x(575); theEnemy->SetPos_y(100); theArrayOfGoodies = new CGoodies*[10]; for (int i=0; i<10; i++) { theArrayOfGoodies[i] = theGoodiesFactory.Create( TREASURECHEST ); theArrayOfGoodies[i]->SetPos( 150 + i*25, 150 ); theArrayOfGoodies[i]->SetMesh(MeshBuilder::Generate2DMesh("GEO_TILE_TREASURECHEST", Color(1, 1, 1), 0, 0, 25, 25)); theArrayOfGoodies[i]->SetTextureID(LoadTGA("Image//tile4_treasurechest.tga")); } */ // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 1000 units Mtx44 perspective; perspective.SetToPerspective(45.0f, 4.0f / 3.0f, 0.1f, 10000.0f); //perspective.SetToOrtho(-80, 80, -60, 60, -1000, 1000); projectionStack.LoadMatrix(perspective); rotateAngle = 0; m_save = new Save(); m_player = new Player(); m_player->PlayerInit("Player.lua"); //initailise grid system Playfield = new GridSystem(); // in this order: position of the whole grid system, size of grid x, size of grid y, number of grid x, number of grid y Playfield->Init(Vector3(400, 300, 0), 25.f, 25.f, 5, 5); AddHighscore(); }
void CChildView::InitGL() { // Create a checkerboard pattern for (int i = 0; i < 64; i++) { for (int j = 0; j < 64; j++) { GLubyte c; c = (((i & 0x8) == 0) ^ ((j & 0x8) == 0)) * 255; image[i][j][0] = c; image[i][j][1] = c; image[i][j][2] = c; image2[i][j][0] = c; image2[i][j][1] = 0; image2[i][j][2] = c; } } colorcube(); m_program = LoadShaders( "ShaderWnd/vertex.glsl", "ShaderWnd/fragment.glsl" ); static const vec4 g_vertex_buffer_data[] = { vec4(-1.0f, -1.0f, 0.0f, 1.0f), vec4(1.0f, -1.0f, 0.0f, 1.0f), vec4(0.0f, 0.5f, 0.0f, 1.0f) }; static const vec4 g_color_buffer_data[] = { vec4(1.0f, 0.0f, 0.0f, 1.0f), vec4(0.0f, 1.0f, 0.0f, 1.0f), vec4(0.0f, 0.0f, 1.0f, 1.0f) }; //GLuint vertexbuffer; glUseProgram(m_program); GLuint vao; glGenVertexArrays( 1, &vao); glBindVertexArray( vao); /*glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);*/ glGenTextures(2, textures); glBindTexture(GL_TEXTURE_2D, textures[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, TextureSize,TextureSize, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, textures[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, TextureSize,TextureSize, 0, GL_RGB, GL_UNSIGNED_BYTE, image2); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glActiveTexture( GL_TEXTURE0 ); glBindTexture( GL_TEXTURE_2D, textures[0]); glActiveTexture( GL_TEXTURE1 ); glBindTexture( GL_TEXTURE_2D, textures[1]); // Create and initialize a buffer object GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(points) + sizeof(tex_coords) + sizeof(normals), NULL, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(points), value_ptr(points[0])); glBufferSubData(GL_ARRAY_BUFFER, sizeof(points), sizeof(normals), value_ptr(normals[0])); glBufferSubData(GL_ARRAY_BUFFER, sizeof(points) + sizeof(normals), sizeof(tex_coords), value_ptr(tex_coords[0])); point4 light_position (-5.f, 5.f, -5.f, 0.f); color4 light_ambient (0.2f, 0.2f, 0.2f, 1.f); color4 light_diffuse (1.f, 1.f, 1.f, 1.f); color4 light_specular (1.f, 1.f, 1.f, 1.f); color4 material_ambient(.3f, .6f, .3f, 1.f); color4 material_diffuse (0.3f, .6f, 0.3f, 1.f); color4 material_specular (1.f, 1.f, 1.f, 1.f); float material_shininess = 100.0f; color4 ambient_product = light_ambient*material_ambient; color4 diffuse_product = light_diffuse*material_diffuse; color4 specular_product = light_specular*material_specular; glUniform4fv(glGetUniformLocation(m_program, "AmbientProduct"), 1, value_ptr(ambient_product)); glUniform4fv(glGetUniformLocation(m_program, "DiffuseProduct"), 1, value_ptr(diffuse_product)); glUniform4fv(glGetUniformLocation(m_program, "SpecularProduct"), 1, value_ptr(specular_product)); glUniform4fv(glGetUniformLocation(m_program, "LightPosition"), 1, value_ptr(light_position)); glUniform1f(glGetUniformLocation(m_program, "Shininess"), material_shininess); // set up vertex arrays (after shaders are loaded) GLuint vPosition = glGetAttribLocation(m_program, "vPosition"); glEnableVertexAttribArray(vPosition); glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); GLuint vNormal = glGetAttribLocation(m_program, "vNormal"); glEnableVertexAttribArray(vNormal); glVertexAttribPointer(vNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(points))); GLuint vTex = glGetAttribLocation(m_program, "vTexCoord"); glEnableVertexAttribArray(vTex); glVertexAttribPointer(vTex, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(points)+sizeof(normals))); // Set the value of the fragment shader texture sampler variable // ("texture") to the the appropriate texture unit. In this case, // zero, for GL_TEXTURE0 which was previously set by calling // glActiveTexture(). glUniform1i( glGetUniformLocation(m_program, "diffuse_mat"), 0); m_nPVM = glGetUniformLocation(m_program, "mPVM"); m_nVM = glGetUniformLocation(m_program, "mVM"); glClearColor(1.f,1.f,1.f,1.f); glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); }
int main(void) { //Set the error callback glfwSetErrorCallback(error_callback); //Initialize GLFW if (!glfwInit()) { exit(EXIT_FAILURE); } //Set the GLFW window creation hints - these are optional //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version //glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //Create a window and create its OpenGL context window = glfwCreateWindow(960, 720, "Test Window", NULL, NULL); //If the window couldn't be created if (!window) { fprintf(stderr, "Failed to open GLFW window.\n"); glfwTerminate(); //exit(EXIT_FAILURE); } //This function makes the context of the specified window current on the calling thread. glfwMakeContextCurrent(window); //Sets the key callback glfwSetKeyCallback(window, key_callback); //Initialize GLEW GLenum err = glewInit(); //If GLEW hasn't initialized if (err != GLEW_OK) { fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); return -1; } //Set a background color glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glfwSetCursorPos(window, 1024 / 2, 768 / 2); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); // Create and compile our GLSL program from the shaders GLuint red = LoadShaders("SimpleTransform.vertexshader", "SingleColorRed.fragmentshader"); GLuint grid = LoadShaders("SimpleTransform.vertexshader", "SingleColorGrid.fragmentshader"); glBindFragDataLocation(red, 0, "red"); glBindFragDataLocation(grid, 1, "grid"); // Get a handle for our "MVP" uniform GLuint MatrixID = glGetUniformLocation(red, "MVP"); // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 1000.0f); // Or, for an ortho camera : //glm::mat4 Projection = glm::ortho(-10.0f,10.0f,-10.0f,10.0f,0.0f,100.0f); // In world coordinates // Camera matrix glm::mat4 View = glm::lookAt( glm::vec3(4, 3, 3), // Camera is at (4,3,3), in World Space glm::vec3(0, 0, 0), // and looks at the origin glm::vec3(0, 1, 0) // Head is up (set to 0,-1,0 to look upside-down) ); static const GLfloat g_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; static const GLushort g_element_buffer_data[] = { 0, 1, 2 }; GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); static const GLfloat g_triangle_buffer_data[] = { -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, }; GLuint triangle; glGenBuffers(1, &triangle); glBindBuffer(GL_ARRAY_BUFFER, triangle); glBufferData(GL_ARRAY_BUFFER, sizeof(g_triangle_buffer_data), g_triangle_buffer_data, GL_STATIC_DRAW); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); glEnable(GL_LIGHTING); glEnable(GL_SMOOTH);//OPENGL INSTANTIATION HRESULT hr; NUI_IMAGE_FRAME depthFrame; HANDLE hDepth; INuiSensor* pNuiSensor = NULL; int iSensorCount = 0; hr = NuiGetSensorCount(&iSensorCount); if (FAILED(hr)) return hr; for (int i = 0; i < iSensorCount; i++) { INuiSensor* tempSensor; hr = NuiCreateSensorByIndex(i, &tempSensor); if (FAILED(hr)) continue; hr = tempSensor->NuiStatus(); if (S_OK == hr) { pNuiSensor = tempSensor; break; } tempSensor->Release(); } for (int i = 0; i < 2048; i++) { depthLookUp[i] = rawDepthToMeters(i); } rotation = getRotationMatrix(theta, psi, fi); pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_DEPTH); pNuiSensor->NuiImageStreamOpen( NUI_IMAGE_TYPE_DEPTH, NUI_IMAGE_RESOLUTION_320x240, 0, 2, NULL, &hDepth);//KINECT INSTANTIATION cout << "Starting Main Loop"; static double lastTime = glfwGetTime(); //Main Loop do { double currentTime = glfwGetTime(); float deltaTime = float(currentTime - lastTime); //Clear color buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(grid); modelMatrix(MatrixID); hr = pNuiSensor->NuiImageStreamGetNextFrame(hDepth, 0, &depthFrame); if (!FAILED(hr)) { INuiFrameTexture* pTexture; NUI_LOCKED_RECT LockedRect; hr = pNuiSensor->NuiImageFrameGetDepthImagePixelFrameTexture( hDepth, &depthFrame, false, &pTexture); if (FAILED(hr)) { pNuiSensor->NuiImageStreamReleaseFrame(hDepth, &depthFrame); continue; } pTexture->LockRect(0, &LockedRect, NULL, 0);//Kinect Image Grab int skipX = 1; int skipY = 1; float scalar = 4.0f; if (LockedRect.Pitch != 0) { for (int x = 0; x < width; x += skipX) { for (int y = 0; y < height; y += skipY) { const NUI_DEPTH_IMAGE_PIXEL * pBufferRun = reinterpret_cast<const NUI_DEPTH_IMAGE_PIXEL *>(LockedRect.pBits) + x + y * width; //float depth = (float)(pBufferRun->depth); //glm::vec3 location = realWorld(depth, height - y, x, 500.0f, 1000.0f); //createCube(0.006f, location); Vector4 locationDepth = NuiTransformDepthImageToSkeleton(x, y, (short)(pBufferRun->depth << 3)); glm::vec3 locationDepthxyz = glm::vec3(locationDepth.x * scalar, locationDepth.y * scalar, locationDepth.z * scalar); createCube(0.009f, locationDepthxyz); } } } pTexture->UnlockRect(0); pTexture->Release(); pNuiSensor->NuiImageStreamReleaseFrame(hDepth, &depthFrame); } createGrid(); //Test drawings /* glUseProgram(red); modelMatrix(MatrixID); //createCube(0.05f, glm::vec3(1.0f,1.0f,1.0f)); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); //createObject(vertexbuffer, GL_TRIANGLES, 3); //createObject(triangle, GL_TRIANGLES, 3); glDisableVertexAttribArray(0); */ //Swap buffers glfwSwapBuffers(window); //Get and organize events, like keyboard and mouse input, window resizing, etc... glfwPollEvents(); std::string title = "Title | DELTA TIME " + std::to_string(1.0f/deltaTime); const char* pszConstString = title.c_str(); glfwSetWindowTitle(window, pszConstString); lastTime = currentTime; } //Check if the ESC key had been pressed or if the window had been closed while (!glfwWindowShouldClose(window)); //Close OpenGL window and terminate GLFW glfwDestroyWindow(window); //Finalize and clean up GLFW glfwTerminate(); exit(EXIT_SUCCESS); }
/*!**************************************************************************** @Function InitView @Return bool true if no error occurred @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES2Glass::InitView() { CPVRTString ErrorStr; // Store the original FBO handle glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_iOriginalFramebuffer); /* Initialize VBO data */ LoadVbos(); if (!LoadParaboloids(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } /* Load textures */ if (!LoadTextures(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } /* Load and compile the shaders & link programs */ if (!LoadShaders(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Is the screen rotated? bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); /* Initialize Print3D */ if(m_Print3D.SetTextures(0,PVRShellGet(prefWidth),PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } // Set the sampler2D uniforms to corresponding texture units glUseProgram(m_DefaultProgram.uiId); glUniform1i(glGetUniformLocation(m_DefaultProgram.uiId, "s2DMap"), 0); glUseProgram(m_SkyboxProgram.uiId); glUniform1i(glGetUniformLocation(m_SkyboxProgram.uiId, "sSkybox"), 0); glUseProgram(m_ParaboloidProgram.uiId); glUniform1i(glGetUniformLocation(m_ParaboloidProgram.uiId, "s2DMap"), 0); glUniform1f(glGetUniformLocation(m_ParaboloidProgram.uiId, "Near"), g_fCamNear); glUniform1f(glGetUniformLocation(m_ParaboloidProgram.uiId, "Far"), g_fCamFar); for (int i = 0; i < g_iNumEffects; ++i) { glUseProgram(m_aEffectPrograms[i].uiId); glUniform1i(glGetUniformLocation(m_aEffectPrograms[i].uiId, "sParaboloids"), 0); glUniform1i(glGetUniformLocation(m_aEffectPrograms[i].uiId, "sSkybox"), 1); } /* Calculate the projection and view matrices */ m_mProjection = PVRTMat4::PerspectiveFovRH(g_fCamFOV, (float)PVRShellGet(prefWidth)/(float)PVRShellGet(prefHeight), g_fCamNear, g_fCamFar, PVRTMat4::OGL, bRotate); /* Set OpenGL ES render states needed for this training course */ // Enable backface culling and depth test glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); // Use a nice bright blue as clear colour glClearColor(0.6f, 0.8f, 1.0f, 0.0f); return true; }
/*!**************************************************************************** @Function InitView @Return bool true if no error occured @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES2Refraction::InitView() { CPVRTString ErrorStr; /* Initialize VBO data */ LoadVbos(); /* Load textures */ if (!LoadTextures(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } /* Load and compile the shaders & link programs */ if (!LoadShaders(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Set the sampler2D uniforms to corresponding texture units glUniform1i(glGetUniformLocation(m_ShaderProgram.uiId, "sTexture"), 0); // Is the screen rotated? m_bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); /* Initialize Print3D */ if(m_Print3D.SetTextures(0,PVRShellGet(prefWidth),PVRShellGet(prefHeight), m_bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } /* Initalise the background */ if(m_Background.Init(0, m_bRotate, &ErrorStr) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } /* Calculate the projection and view matrices */ m_mProjection = PVRTMat4::PerspectiveFovRH(PVRT_PI/6, (float)PVRShellGet(prefWidth)/(float)PVRShellGet(prefHeight), CAM_NEAR, CAM_FAR, PVRTMat4::OGL, m_bRotate); m_mView = PVRTMat4::LookAtRH(PVRTVec3(0, 0, 150), PVRTVec3(0, 0, 0), PVRTVec3(0, 1, 0)); /* Set OpenGL ES render states needed for this training course */ // Use a nice bright blue as clear colour glClearColor(0.6f, 0.8f, 1.0f, 1.0f); return true; }
// initialises the gWoodenCrate global static void LoadWoodenCrateAsset() { // set all the elements of gWoodenCrate gWoodenCrate.shaders = LoadShaders("vertex-shader.txt", "fragment-shader.txt"); gWoodenCrate.drawType = GL_TRIANGLES; gWoodenCrate.drawStart = 0; gWoodenCrate.drawCount = 6*2*3; gWoodenCrate.texture = LoadTexture("wooden-crate.jpg"); glGenBuffers(1, &gWoodenCrate.vbo); glGenVertexArrays(1, &gWoodenCrate.vao); // bind the VAO glBindVertexArray(gWoodenCrate.vao); // bind the VBO glBindBuffer(GL_ARRAY_BUFFER, gWoodenCrate.vbo); // Make a cube out of triangles (two triangles per side) GLfloat vertexData[] = { // X Y Z U V // bottom -1.0f,-1.0f,-1.0f, 0.0f, 0.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, // top -1.0f, 1.0f,-1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 1.0f,-1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // front -1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f,-1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // back -1.0f,-1.0f,-1.0f, 0.0f, 0.0f, -1.0f, 1.0f,-1.0f, 0.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, -1.0f, 1.0f,-1.0f, 0.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, // left -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 0.0f, -1.0f,-1.0f,-1.0f, 0.0f, 0.0f, -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 0.0f, // right 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 1.0f,-1.0f, 0.0f, 0.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f }; glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); // connect the xyz to the "vert" attribute of the vertex shader glEnableVertexAttribArray(gWoodenCrate.shaders->attrib("vert")); glVertexAttribPointer(gWoodenCrate.shaders->attrib("vert"), 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), NULL); // connect the uv coords to the "vertTexCoord" attribute of the vertex shader glEnableVertexAttribArray(gWoodenCrate.shaders->attrib("vertTexCoord")); glVertexAttribPointer(gWoodenCrate.shaders->attrib("vertTexCoord"), 2, GL_FLOAT, GL_TRUE, 5*sizeof(GLfloat), (const GLvoid*)(3 * sizeof(GLfloat))); // unbind the VAO glBindVertexArray(0); }
void initScene() { print4x4FMatrix("modelViewMatrix",modelViewMatrix); int viewport[4]={0}; buildOpenGLProjectionForIntrinsics ( projectionMatrix , viewport , fx, fy, 0.0 , // SKEW windowWidth/2.0, windowHeight/2.0, windowWidth, windowHeight, near, far ); print4x4FMatrix("projectionMatrix",projectionMatrix); lightPosition[0]=2; lightPosition[1]=2; lightPosition[2]=2; //create4x4RotationMatrix(modelViewProjection , 30 , 1.0, 1.0 , 1.0 ); camera.pos[0]=0; camera.pos[1]=0; camera.pos[2]=-3; camera.angle[0]=0; camera.angle[1]=0; camera.angle[2]=0; camera.angle[3]=0; updateView(0); //generate and bind a VAO for the 3D axes glGenVertexArrays(1, &vao); checkOpenGLError(__FILE__, __LINE__); glBindVertexArray(vao); checkOpenGLError(__FILE__, __LINE__); //colorcube(); // Load shaders and use the resulting shader program #if USE_SIMPLE_SHADERS fprintf(stderr,GREEN "Loading simple shader set \n" NORMAL); program = LoadShaders( "simple.vert", "simple.frag" ); checkOpenGLError(__FILE__, __LINE__); #else fprintf(stderr,GREEN "Loading complex shader set \n" NORMAL); program = LoadShaders( "test.vert", "test.frag" ); checkOpenGLError(__FILE__, __LINE__); #endif // USE_SIMPLE_SHADERS glUseProgram( program ); checkOpenGLError(__FILE__, __LINE__); // Create and initialize a buffer object on the server side (GPU) glGenBuffers( 1, &buffer ); checkOpenGLError(__FILE__, __LINE__); glBindBuffer( GL_ARRAY_BUFFER, buffer ); checkOpenGLError(__FILE__, __LINE__); NumVertices=0; //pushObjectToBufferData( heartVertices , sizeof(heartVertices) , heartNormals , sizeof(heartNormals) , 0 , 0 ); //pushObjectToBufferData( cubeCoords , sizeof(cubeCoords) , cubeNormals , sizeof(cubeNormals) , 0 , 0 ); //pushObjectToBufferData( planeCoords , sizeof(planeCoords) , planeNormals , sizeof(planeNormals) , 0 , 0 ); pushObjectToBufferData( pyramidCoords , sizeof(pyramidCoords) , pyramidNormals , sizeof(pyramidNormals) , 0 , 0 ); lightPositionLocation = glGetUniformLocation( program, "lightPosition" ); checkOpenGLError(__FILE__, __LINE__); fogLocation = glGetUniformLocation( program, "fogColorAndScale" ); checkOpenGLError(__FILE__, __LINE__); lightColorLocation = glGetUniformLocation( program, "lightColor" ); checkOpenGLError(__FILE__, __LINE__); lightMaterialsLocation = glGetUniformLocation( program, "lightMaterials" ); checkOpenGLError(__FILE__, __LINE__); normalTransformationLocation = glGetUniformLocation(program, "normalTransformation"); checkOpenGLError(__FILE__, __LINE__); modelViewProjectionMatrixLocation = glGetUniformLocation(program, "modelViewProjection"); checkOpenGLError(__FILE__, __LINE__); modelViewMatrixLocation = glGetUniformLocation(program, "modelViewMatrix"); checkOpenGLError(__FILE__, __LINE__); updateView(1); glEnable( GL_DEPTH_TEST ); glClearColor( 0.0, 0.0, 0.0, 1.0 ); checkOpenGLError(__FILE__, __LINE__); // only one VAO can be bound at a time, so disable it to avoid altering it accidentally glBindVertexArray(0); checkOpenGLError(__FILE__, __LINE__); }
int main(int argc, char **argv) { if(argc != 2) exit(0); if(!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(1920, 1080, "Audio Visualization", glfwGetPrimaryMonitor(), NULL); if(window == NULL) { fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = true; //Needed for core profile if(glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetInputMode(window, GLFW_CURSOR_DISABLED, GL_TRUE); // glClearColor(0.f / 255.f, 63.f / 255.f, 0.f / 255.f, 1.0f); glClearColor(0.1, 0.1, 0.1, 1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); /* ShaderInfo shaders[] = { {GL_VERTEX_SHADER, "VertexShader.vert"}, {GL_FRAGMENT_SHADER, "FragmentShader.frag"}, {GL_GEOMETRY_SHADER, "GeometryShader.geom"}, {GL_NONE, NULL}}; GLuint programID = LoadShaders(shaders);*/ GLuint programID = LoadShaders("shaders/VertexShader.vert", "shaders/FragmentShader.frag", NULL);//"shaders/GeometryShader.geom"); GLuint MatrixID = glGetUniformLocation(programID, "MVP"); GLuint objectID = glGetUniformLocation(programID, "object"); GLuint topID = glGetUniformLocation(programID, "top"); glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f); glm::mat4 View = glm::lookAt( glm::vec3(10,15,20), //Camera is at (4,3,-3), in World Space glm::vec3(0,0,0), //and looks at the origin glm::vec3(0,1,0)); //Head is up (set to 0,-1,0 to look upside-down) glm::mat4 Model = glm::mat4(1.0f); glm::mat4 PV = Projection * View; glm::mat4 MVP = PV * Model; static const GLfloat g_vertex_buffer_data1[] = { -1.0f,-1.0f,-1.0f, //left -1.0f,-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, //right 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, //front 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, //top 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f,-1.0f, //back 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 1.0f,-1.0f, -1.0f,-1.0f,-1.0f, //bottom 1.0f,-1.0f,-1.0f, 1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f }; static const GLfloat g_vertex_buffer_data2[] = { -1.0f,-1.0f,-1.0f, //left -1.0f,-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, //right 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, //front 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, //top 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f,-1.0f, //back 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 1.0f,-1.0f, -1.0f,-1.0f,-1.0f, //bottom 1.0f,-1.0f,-1.0f, 1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f }; static const GLfloat g_color_buffer_data1[] = { 1.0f, 0.2f, 0.2f, //left 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 0.2f, //right 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, //front 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, //top 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 0.2f, //back 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 0.5f, 0.5f, 1.0f, 0.2f, 0.2f, //bottom 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 0.5f, 0.5f }; static const GLfloat g_color_buffer_data2[] = { 0.2f, 0.2f, 1.0f, //left 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 0.2f, 1.0f, //right 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 1.0f, //front 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 1.0f, //top 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 0.2f, 1.0f, //back 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 0.5f, 0.5f, 1.0f, 0.2f, 0.2f, 1.0f, //bottom 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 0.2f, 0.2f, 1.0f, 0.5f, 0.5f, 1.0f, 0.5f, 0.5f, 1.0f }; GLuint vertexbuffer1; //left column glGenBuffers(1, &vertexbuffer1); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer1); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data1), g_vertex_buffer_data1, GL_STATIC_DRAW); GLuint vertexbuffer2; //right column glGenBuffers(1, &vertexbuffer2); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer2); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data2), g_vertex_buffer_data2, GL_STATIC_DRAW); GLuint vertexbuffer3; //waveform glGenBuffers(1, &vertexbuffer3); GLuint vertexbuffer4; //z glGenBuffers(1, &vertexbuffer4); GLuint vertexbuffer5; //spectrum glGenBuffers(1, &vertexbuffer5); GLuint colorbuffer1; glGenBuffers(1, &colorbuffer1); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer1); glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data1), g_color_buffer_data1, GL_STATIC_DRAW); GLuint colorbuffer2; glGenBuffers(1, &colorbuffer2); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer2); glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data2), g_color_buffer_data2, GL_STATIC_DRAW); audio_data data = get_audio_data(argv[1]); int bpf = data.sampling_rate / fps; int data_index = 0; double current_time; double last_time; double total_time = data.size / data.sampling_rate / 4; float z[bpf * 2]; for(int i = 0; i < bpf; i++) z[i * 2] = z[i * 2 + 1] = waveform_length / bpf * i - waveform_length / 2; glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer4); glBufferData(GL_ARRAY_BUFFER, bpf * 8, z, GL_STATIC_DRAW); int res; pthread_t a_thread; void *thread_result; res = pthread_create(&a_thread, NULL, play_wav_d, argv[1]); if(res != 0) { perror("Thread creation failed!"); exit(EXIT_FAILURE); } FFT fft; fft.setDataSize(bpf); fft.setSampleRate(data.sampling_rate); float max_l = 0, max_r = 0; glfwSetTime(0); do { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programID); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); computeMatricesFromInputs(); glm::mat4 Projection = getProjectionMatrix(); glm::mat4 View = getViewMatrix(); glm::mat4 ModelMatrix = glm::mat4(1.0); PV = Projection * View; MVP = PV * ModelMatrix; glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); float *FFTdata = fft.calculateFFT((short *)data.data + data_index); int spectrum_interval = fps / 2; for(int i = 0; i < bpf; i++) { for(int j = 1; j < spectrum_interval; j++) FFTdata[i * spectrum_interval] += FFTdata[i * spectrum_interval + j]; FFTdata[i * spectrum_interval] /= spectrum_interval * 10; FFTdata[i * spectrum_interval + spectrum_interval / 2] = 0; } glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer4); //z glVertexAttribPointer( 2, //attribute. No particular reason for 0, but must match the layout in the shader. 1, //size GL_FLOAT, //type GL_FALSE, //normalized? 0, //stride (void *)0 //array buffer offset ); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer5); //spectrum glBufferData(GL_ARRAY_BUFFER, spectrum_interval * bpf * 4, FFTdata, GL_STATIC_DRAW); glVertexAttribPointer( 0, //attribute. No particular reason for 0, but must match the layout in the shader. 1, //size GL_FLOAT, //type GL_FALSE, //normalized? spectrum_interval * 2, //stride (void *)0 //array buffer offset ); glUniform1i(objectID, 6); glDrawArrays(GL_LINES, 0, bpf * 2); //draw spectrum glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer4); //z glVertexAttribPointer( 2, //attribute. No particular reason for 0, but must match the layout in the shader. 1, //size GL_FLOAT, //type GL_FALSE, //normalized? (waveform_interval + 1) * 4, //stride (void *)0 //array buffer offset ); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer3); //waveform glBufferData(GL_ARRAY_BUFFER, bpf * 4, (short *)data.data + data_index, GL_DYNAMIC_DRAW); glVertexAttribPointer( 0, //attribute. No particular reason for 0, but must match the layout in the shader. 1, //size GL_SHORT, //type GL_FALSE, //normalized? waveform_interval * 4, //stride (void *)0 //array buffer offset ); glUniform1i(objectID, 2); glDrawArrays(GL_LINE_STRIP, 0, bpf / waveform_interval); //draw left waveform glVertexAttribPointer( 0, //attribute. No particular reason for 0, but must match the layout in the shader. 1, //size GL_SHORT, //type GL_FALSE, //normalized? waveform_interval * 4, //stride (void *)2 //array buffer offset ); glUniform1i(objectID, 3); glDrawArrays(GL_LINE_STRIP, 0, bpf / waveform_interval); //draw right waveform float sum_l = 0, sum_r = 0; for(int i = 0; i < bpf; i++) { sum_l = max(sum_l, abs(((short*)data.data)[data_index++])); //max sum_r = max(sum_r, abs(((short*)data.data)[data_index++])); // sum_l += abs(((short*)data.data)[data_index++]); //avg // sum_r += abs(((short*)data.data)[data_index++]); } // sum_l /= bpf; //avg // sum_r /= bpf; float scale_l = sum_l / 32768 * column_height; Model = glm::mat4( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -2.0, 1.0, 0.0, 1.0); glm::mat4 scale1 = glm::mat4( 1.0, 0.0, 0.0, 0.0, 0.0, scale_l, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); MVP = PV * scale1 * Model; glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer1); //left column vertex glVertexAttribPointer( 0, // attribute. 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 ); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer1); //left column color glVertexAttribPointer( 1, // attribute. No particular reason for 1, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void *)0 // array buffer offset ); glUniform1i(objectID, 0); glDrawArrays(GL_TRIANGLES, 0, 12*3); //draw left column if(scale_l> max_l) max_l = scale_l; else max_l -= top_speed; glm::mat4 translate1 = glm::mat4( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -2.0, max_l * 2, 0.0, 1.0); scale1 = glm::mat4( max_l / 2, 0.0, 0.0, 0.0, 0.0, max_l / 2 * top_height, 0.0, 0.0, 0.0, 0.0, max_l / 2, 0.0, 0.0, 0.0, 0.0, 1.0); MVP = PV * translate1 * scale1; glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniform1i(objectID, 4); glUniform1f(topID, max_l); glDrawArrays(GL_TRIANGLES, 0, 12*3); //draw left upper top translate1 = glm::mat4( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -2.0, scale_l * 2, 0.0, 1.0); scale1 = glm::mat4( scale_l / 2, 0.0, 0.0, 0.0, 0.0, scale_l / 2 * top_height, 0.0, 0.0, 0.0, 0.0, scale_l / 2, 0.0, 0.0, 0.0, 0.0, 1.0); MVP = PV * translate1 * scale1; glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniform1i(objectID, 4); glUniform1f(topID, scale_l); glDrawArrays(GL_TRIANGLES, 0, 12*3); //draw left lower top float scale_r = sum_r / 32768 * column_height; Model = glm::mat4( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 2.0, 1.0, 0.0, 1.0); glm::mat4 scale2 = glm::mat4( 1.0, 0.0, 0.0, 0.0, 0.0, scale_r, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); MVP = PV * scale2 * Model; glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer2); //right column vertex glVertexAttribPointer( 0, // attribute. 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 ); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer2); //right column vertex glVertexAttribPointer( 1, // attribute. No particular reason for 1, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glUniform1i(objectID, 1); glDrawArrays(GL_TRIANGLES, 0, 12*3); //draw right column if(scale_r > max_r) max_r = scale_r; else max_r -= top_speed; glm::mat4 translate2 = glm::mat4( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 2.0, max_r * 2, 0.0, 1.0); scale2 = glm::mat4( max_r / 2, 0.0, 0.0, 0.0, 0.0, max_r / 2 * top_height, 0.0, 0.0, 0.0, 0.0, max_r / 2, 0.0, 0.0, 0.0, 0.0, 1.0);//0.25 / max_r);//(4.0 - max_r) * (4.0 - max_r)); MVP = PV * translate2 * scale2; glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniform1i(objectID, 5); glUniform1f(topID, max_r); glDrawArrays(GL_TRIANGLES, 0, 12*3); //draw right upper top translate2 = glm::mat4( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 2.0, scale_r * 2, 0.0, 1.0); scale2 = glm::mat4( scale_r / 2, 0.0, 0.0, 0.0, 0.0, scale_r / 2 * top_height, 0.0, 0.0, 0.0, 0.0, scale_r / 2, 0.0, 0.0, 0.0, 0.0, 1.0);//0.25 / max_r);//(4.0 - max_r) * (4.0 - max_r)); MVP = PV * translate2 * scale2; glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniform1i(objectID, 5); glUniform1f(topID, scale_r); glDrawArrays(GL_TRIANGLES, 0, 12*3); //draw right lower top glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); if(data_index >= data.size / 2) break; current_time = glfwGetTime(); double left_time = total_time - current_time; if(left_time <= 0) break; double accurate_time = data_index / 2.0 / bpf / fps; double delta = accurate_time - current_time; printf("%lf %lf %lf %lf %lf\n", current_time - last_time, accurate_time, current_time, delta, left_time); delta = delta > 0 ? delta : 0; last_time = current_time; usleep(delta * 1000000); glfwSwapBuffers(window); glfwPollEvents(); } while(glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && !glfwWindowShouldClose(window)); pthread_cancel(a_thread); res = pthread_join(a_thread, &thread_result); if(res != 0) { perror("Thread join failed!"); exit(EXIT_FAILURE); } glDeleteBuffers(1, &vertexbuffer1); glDeleteBuffers(1, &vertexbuffer2); glDeleteBuffers(1, &vertexbuffer3); glDeleteBuffers(1, &vertexbuffer4); glDeleteBuffers(1, &vertexbuffer5); glDeleteBuffers(1, &colorbuffer1); glDeleteBuffers(1, &colorbuffer2); glDeleteProgram(programID); glDeleteVertexArrays(1, &VertexArrayID); glfwTerminate(); return 0; }
int _tmain(int argc, _TCHAR* argv[]) { GLFWwindow* window = 0; glfwSetErrorCallback(glfw_error_callback_func); // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); getchar(); return -1; } //----------------------------------------------------------------------------- glfwWindowHint(GLFW_SAMPLES, 4); // GL3.3 Core profile glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_VISIBLE, 0); //オフスクリーン // Open a window and create its OpenGL context window = glfwCreateWindow(1, 1, "GPGPU Test", NULL, NULL); if (window == NULL){ fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); getchar(); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); #if defined _WIN32 // Initialize GLEW glewExperimental = GL_TRUE; ///!!!! important for core profile // コアプロファイルで必要となります if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); getchar(); glfwTerminate(); return -1; } #endif { cout << "GL_VENDOR:" << glGetString(GL_VENDOR) << endl; cout << "GL_RENDERER:" << glGetString(GL_RENDERER) << endl; cout << "GL_VERSION:" << glGetString(GL_VERSION) << endl; cout << "GL_SHADING_LANGUAGE_VERSION:" << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; } #ifdef _DEBUG Mat imgSrc = Mat(Size(8, 4), CV_32FC1); #else Mat imgSrc = Mat(Size(1024, 1024), CV_32FC1); #endif Mat imgDst = Mat::zeros(imgSrc.size(), imgSrc.type()); Mat imgRef = Mat::zeros(imgSrc.size(), imgSrc.type()); //世代 #ifdef _DEBUG const int generations = 1; // const int generations = 3; #else const int generations = 1000; #endif { cout << "Cell Size:" << imgSrc.size() << endl; cout << "generations:" << generations << endl; } //--------------------------------- //init Src image initCellLife(imgSrc); //--------------------------------- //Execute GPGPU { cout << "Execute GPGPU" << endl; const int width = imgSrc.cols; const int height = imgSrc.rows; // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders("LifeGame.vertexshader", "LifeGameUpdate.fragmentshader"); // texture enum E_TextureID{ SRC, DST, SIZEOF, }; unsigned int textureID[E_TextureID::SIZEOF]; //src dst //--------------------------------- // CreateTexture { GLenum format = GL_RED; //single channel GLenum type = GL_FLOAT; //float GLenum internalFormat = GL_R32F; //single channel float glGenTextures(sizeof(textureID) / sizeof(textureID[0]), textureID); // create (reference to) a new texture for (int i = 0; i < sizeof(textureID) / sizeof(textureID[0]); i++){ glBindTexture(GL_TEXTURE_2D, textureID[i]); // (set texture parameters here) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #ifdef LIFE_BOUND_REPEAT glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); #else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); #endif //create the texture glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, 0); glBindTexture(GL_TEXTURE_2D, 0); } } //upload imgSrc to texture { //Timer tmr("upload:"); GLenum format = GL_RED; //single channel GLenum type = GL_FLOAT; //float void* data = imgSrc.data; glBindTexture(GL_TEXTURE_2D, textureID[E_TextureID::SRC]); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data); glBindTexture(GL_TEXTURE_2D, 0); } // FBO identifier GLuint fbo = 0; //--------------------------------- // FBO // create FBO (off-screen framebuffer) glGenFramebuffers(1, &fbo); // bind offscreen framebuffer (that is, skip the window-specific render target) // glBindFramebuffer(GL_FRAMEBUFFER, fbo); //Execute { Timer tmr("LifeGame@gpu:"); for (int i = 0; i < generations; i++){ GLuint texSrc = textureID[(i % 2)]; GLuint texDst = textureID[(i % 2) ^ 1]; executeGpGpuProcess(programID, fbo, texSrc, texDst); } } { //download from framebuffer //Timer tmr("download:"); GLenum format = GL_RED; //single channel GLenum type = GL_FLOAT; //float void* data = imgDst.data; int width = imgDst.cols; int height = imgDst.rows; //wait for Rendering glFinish(); // ReadBuffer glReadBuffer(GL_COLOR_ATTACHMENT0); // ReadPixels glReadPixels(0, 0, width, height, format, type, data); } //clean up glDeleteTextures(sizeof(textureID) / sizeof(textureID[0]), textureID); glDeleteFramebuffers(1, &fbo); glDeleteProgram(programID); } //--------------------------------- //Execute CPU { cout << "Execute CPU" << endl; Mat imgBank[2] = { Mat::zeros(imgSrc.size(), imgSrc.type()), Mat::zeros(imgSrc.size(), imgSrc.type()) }; int bank = 0; imgBank[bank] = imgSrc.clone(); { Timer tmr("LifeGame@cpu:"); for (int i = 0; i < generations; i++){ updateCellLife(imgBank[bank], imgBank[bank ^ 1]); bank = bank ^ 1; } } imgRef = imgBank[bank].clone(); } #ifdef _DEBUG //dump { cout << "imgSrc" << endl; cout << imgSrc << endl; cout << "imgDst" << endl; cout << imgDst << endl; cout << "imgRef" << endl; cout << imgRef << endl; } #endif //verify int errNum = 0; { //verify int width = imgSrc.cols; int height = imgSrc.rows; for (int y = 0; y < height; y++){ for (int x = 0; x < width; x++){ float ref = imgRef.at<float>(y, x); float dst = imgDst.at<float>(y, x); if (ref != dst) errNum++; } } cout << "ErrNum:" << errNum << endl; } #if 0 //visualize { imshow("src", imgSrc); imshow("dst", imgDst); imshow("ref", imgRef); waitKey(); } #endif // Close OpenGL window and terminate GLFW glfwTerminate(); cout << "Hit return key" << endl; cin.get(); return errNum; }
void SetupGL() // { //Parameter handling glShadeModel (GL_SMOOTH); glEnable(GL_DEPTH_TEST); // polygon rendering mode glEnable(GL_COLOR_MATERIAL); glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE ); //Set up light source GLfloat light_position[] = { 0.0, 30.0,-50.0,0.0 }; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); // Black background glClearColor(0.0f,0.0f,0.0f,1.0f); // Register GLUT callbacks glutDisplayFunc(DisplayGL); glutKeyboardFunc(KeyboardGL); glutReshapeFunc(ReshapeGL); // Setup initial GL State glClearColor( 1.0f, 1.0f, 1.0f, 1.0f ); glClearDepth( 1.0f ); // // Init GLEW if ( glewInit() != GLEW_OK ) { std::cerr << "Failed to initialize GLEW." << std::endl; exit(-1); } // Setup initial GL State glClearColor( 0.3f, 0.3f, 0.3f, 1.0f ); glClearDepth( 1.0f ); std::cout << "Initialise OpenGL: Success!" << std::endl; //VAO // glGenVertexArrays(1, &VertexArrayID); // glBindVertexArray(VertexArrayID); // Create and compile our GLSL program from the shaders programID = LoadShaders( "SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader" ); //VBO static const GLfloat g_vertex_buffer_data[] = { -1.0f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -1.0f, 1.0f, 0.0f, }; static const GLfloat g_vertex_buffer_data2[] = { -1.0f, -1.0f, 0.0f, -0.3f, -1.0f, 0.0f, -1.0f, -0.3f, 0.0f, 1.0f, 1.0f, 0.0f, 0.3f, 1.0f, 0.0f, 1.0f, 0.3f, 0.0f, -0.2f, -0.2f, 0.0f, 0.2f, -0.2f, 0.0f, 0.2f, 0.2f, 0.0f, }; // Generate 1 buffer, put the resulting identifier in vertexbuffer glGenBuffers(1, &vertexbuffer); // The following commands will talk about our 'vertexbuffer' buffer glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); // Give our vertices to OpenGL. glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); //Making and filling my own buffer glGenBuffers(1, &trainglesbuffer); glBindBuffer(GL_ARRAY_BUFFER, trainglesbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data2), g_vertex_buffer_data2, GL_STATIC_DRAW); }
void SceneSkyBox::Init() { // Init VBO here glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Set background color glEnable(GL_DEPTH_TEST); // Enable depth buffer and depth testing glEnable(GL_CULL_FACE); // Enable back face culling glEnable(GL_BLEND); //Enable Blending glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Default to fill mode //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // Generate a default VAO for now glGenVertexArrays(1, &m_vertexArrayID); glBindVertexArray(m_vertexArrayID); m_programID = LoadShaders("Shader//Texture.vertexshader", "Shader//Blending.fragmentshader"); m_parameters[U_MVP] = glGetUniformLocation(m_programID, "MVP"); m_parameters[U_MODELVIEW] = glGetUniformLocation(m_programID, "MV"); m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE] = glGetUniformLocation(m_programID, "MV_inverse_transpose"); m_parameters[U_MATERIAL_AMBIENT] = glGetUniformLocation(m_programID, "material.kAmbient"); m_parameters[U_MATERIAL_DIFFUSE] = glGetUniformLocation(m_programID, "material.kDiffuse"); m_parameters[U_MATERIAL_SPECULAR] = glGetUniformLocation(m_programID, "material.kSpecular"); m_parameters[U_MATERIAL_SHININESS] = glGetUniformLocation(m_programID, "material.kShininess"); m_parameters[U_LIGHT0_POSITION] = glGetUniformLocation(m_programID, "lights[0].position_cameraspace"); m_parameters[U_LIGHT0_COLOR] = glGetUniformLocation(m_programID, "lights[0].color"); m_parameters[U_LIGHT0_POWER] = glGetUniformLocation(m_programID, "lights[0].power"); m_parameters[U_LIGHT0_KC] = glGetUniformLocation(m_programID, "lights[0].kC"); m_parameters[U_LIGHT0_KL] = glGetUniformLocation(m_programID, "lights[0].kL"); m_parameters[U_LIGHT0_KQ] = glGetUniformLocation(m_programID, "lights[0].kQ"); m_parameters[U_LIGHTENABLED] = glGetUniformLocation(m_programID, "lightEnabled"); m_parameters[U_NUMLIGHTS] = glGetUniformLocation(m_programID, "numLights"); //in case you missed out practical 7 // Get a handle for our "colorTexture" uniform m_parameters[U_COLOR_TEXTURE_ENABLED] = glGetUniformLocation(m_programID, "colorTextureEnabled"); m_parameters[U_COLOR_TEXTURE] = glGetUniformLocation(m_programID, "colorTexture"); glUseProgram(m_programID); //variable to rotate geometry //Initialize camera settings camera.Init(Vector3(4, 3, 3), Vector3(0, 0, 0), Vector3(0, 1, 0)); meshList[GEO_AXES] = MeshBuilder::GenerateAxes("AXES", 1000, 1000, 1000); Mtx44 projection; projection.SetToPerspective(45.f, 4.f / 3.f, 0.1f, 1000.f); projectionStack.LoadMatrix(projection); light[0].position.Set(0, 20, 0); light[0].color.Set(1, 1, 1); light[0].power = 1; light[0].kC = 1.f; light[0].kL = 0.01f; light[0].kQ = 0.001f; // Make sure you pass uniform parameters after glUseProgram() glUniform3fv(m_parameters[U_LIGHT0_COLOR], 1, &light[0].color.r); glUniform1f(m_parameters[U_LIGHT0_POWER], light[0].power); glUniform1f(m_parameters[U_LIGHT0_KC], light[0].kC); glUniform1f(m_parameters[U_LIGHT0_KL], light[0].kL); glUniform1f(m_parameters[U_LIGHT0_KQ], light[0].kQ); glUniform1i(m_parameters[U_NUMLIGHTS], 1); meshList[GEO_LIGHTBALL] = MeshBuilder::GenerateSphere("LIGHT", Color(1, 1, 1), 36, 36); meshList[GEO_QUAD] = MeshBuilder::GenerateQuad("quad", Color(1, 1, 1)); meshList[GEO_QUAD]->textureID = LoadTGA("Image//color2.tga"); //Front meshList[GEO_FRONT] = MeshBuilder::GenerateQuad("front", Color(1, 1, 1)); meshList[GEO_FRONT]->textureID = LoadTGA("Image//blizzardfront.tga"); //Back meshList[GEO_BACK] = MeshBuilder::GenerateQuad("back", Color(1, 1, 1)); meshList[GEO_BACK]->textureID = LoadTGA("Image//blizzardback.tga"); //Left meshList[GEO_LEFT] = MeshBuilder::GenerateQuad("left", Color(1, 1, 1)); meshList[GEO_LEFT]->textureID = LoadTGA("Image//blizzardright.tga"); //Right meshList[GEO_RIGHT] = MeshBuilder::GenerateQuad("right", Color(1, 1, 1)); meshList[GEO_RIGHT]->textureID = LoadTGA("Image//blizzardleft.tga"); //Top meshList[GEO_TOP] = MeshBuilder::GenerateQuad("top", Color(1, 1, 1)); meshList[GEO_TOP]->textureID = LoadTGA("Image//blizzardtop.tga"); //Bottom meshList[GEO_BOTTOM] = MeshBuilder::GenerateQuad("quad", Color(1, 1, 1)); meshList[GEO_BOTTOM]->textureID = LoadTGA("Image//blizzardbottom.tga"); //Mario Jumpman Mario meshList[GEO_MARIO] = MeshBuilder::GenerateQuad("Mario", Color(1, 1, 1)); meshList[GEO_MARIO]->textureID = LoadTGA("Image//Mario.tga"); }
/*!**************************************************************************** @Function InitView @Return bool true if no error occured @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES2LevelOfDetail::InitView() { CPVRTString ErrorStr; /* Initialize VBO data */ LoadVbos(); /* Load textures */ if (!LoadTextures(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } /* Load and compile the shaders & link programs */ if (!LoadShaders(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Set the sampler2D uniforms to corresponding texture units glUniform1i(glGetUniformLocation(m_ShaderProgram.uiId, "sReflectTex"), 0); glUniform1i(glGetUniformLocation(m_ShaderProgram.uiId, "sNormalMap"), 1); // Is the screen rotated? bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); /* Initialize Print3D */ if(m_Print3D.SetTextures(0,PVRShellGet(prefWidth),PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } /* Calculate the projection and view matrices */ m_mProjection = PVRTMat4::PerspectiveFovRH(PVRT_PI/6, (float)PVRShellGet(prefWidth)/(float)PVRShellGet(prefHeight), CAM_NEAR, CAM_FAR, PVRTMat4::OGL, bRotate); m_mView = PVRTMat4::LookAtRH(PVRTVec3(0, 0, 150), PVRTVec3(0, 0, 0), PVRTVec3(0, 1, 0)); /* Set OpenGL ES render states needed for this training course */ // Enable backface culling and depth test glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); // Use a nice bright blue as clear colour glClearColor(0.6f, 0.8f, 1.0f, 1.0f); return true; }
void Scene1::Init() { // Init VBO here //Set background color to dark blue // R G B glClearColor(0.0f, 0.0f, 0.4f, 0.0f); //Enable depth test glEnable(GL_DEPTH_TEST); //Generate a default VAO for now //Generate and bind once glGenVertexArrays(1, &m_vertexArrayID); glBindVertexArray(m_vertexArrayID); //Generate buffers into GPU through library glGenBuffers(NUM_GEOMETRY, &m_vertexBuffer[0]); glGenBuffers(NUM_GEOMETRY, &m_colorBuffer[0]); //If you transform things in an array, every vertex will transform as well //An array of 3 vectors which represents 3 verticles static const GLfloat vertex_buffer_data[] = { -0.3f, 0.1f, 0.0f, //vertex 0 of triangle 0.3f, 0.1f, 0.0f, //vertex 1 of triangle 0.0f, -0.1f, 0.0f, //vertex 2 of triangle 0.0f, 0.35f, 0.0f, //vertex 0 of triangle -0.2f, -0.3f, 0.0f, //vertex 1 of triangle 0.0f, -0.1f, 0.0f, //vertex 2 of triangle 0.0f, 0.35f, 0.0f, //vertex 0 of triangle 0.2f, -0.3f, 0.0f, //vertex 1 of triangle 0.0f, -0.1f, 0.0f, //vertex 2 of triangle }; //No neg colors //An array of 3 vectors which represents the colors of the 3 vertices static const GLfloat color_buffer_data[] = { 0.5f, 0.0f, 0.0f, //color of vertex 0 0.5f, 0.0f, 0.0f, //color of vertex 1 0.5f, 0.0f, 0.0f, //color of vertex 2 0.5f, 0.0f, 0.0f, //color of vertex 0 0.5f, 0.0f, 0.0f, //color of vertex 1 0.5f, 0.0f, 0.0f, //color of vertex 2 0.5f, 0.0f, 0.0f, //color of vertex 0 0.5f, 0.0f, 0.0f, //color of vertex 1 0.5f, 0.0f, 0.0f, //color of vertex 2 }; glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer[GEO_TRIANGLE_1]); //Pass the vertex/color data to the GPU at load time (not run time) glBufferData(GL_ARRAY_BUFFER, sizeof(color_buffer_data), color_buffer_data, GL_STATIC_DRAW); //Set the current active buffer glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[GEO_TRIANGLE_1]); //Transfer vertices to openGL glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW); //2nd shape static const GLfloat vertex_buffer_data1[] = { -0.7f, 0.7f, 0.0f, //vertex 0 of triangle 0.0f, 1.0f, 0.0f, //vertex 1 of triangle 0.0f, 0.0f, 0.0f, //vertex 2 of triangle 0.7f, 0.7f, 0.0f, //vertex 0 of triangle 0.0f, 1.0f, 0.0f, //vertex 1 of triangle 0.0f, 0.0f, 0.0f, //vertex 2 of triangle -1.0f, 0.0f, 0.0f, //vertex 0 of triangle -0.7f, 0.7f, 0.0f, //vertex 1 of triangle 0.0f, 0.0f, 0.0f, //vertex 2 of triangle 1.0f, 0.0f, 0.0f, //vertex 0 of triangle 0.7f, 0.7f, 0.0f, //vertex 1 of triangle 0.0f, 0.0f, 0.0f, //vertex 2 of triangle -1.0f, 0.0f, 0.0f, //vertex 0 of triangle -0.7f, -0.7f, 0.0f, //vertex 1 of triangle 0.0f, 0.0f, 0.0f, //vertex 2 of triangle -0.7f, -0.7f, 0.0f, //vertex 0 of triangle 0.0f, -1.0f, 0.0f, //vertex 1 of triangle 0.0f, 0.0f, 0.0f, //vertex 2 of triangle 0.7f, -0.7f, 0.0f, //vertex 0 of triangle 0.0f, -1.0f, 0.0f, //vertex 1 of triangle 0.0f, 0.0f, 0.0f, //vertex 2 of triangle 1.0f, 0.0f, 0.0f, //vertex 0 of triangle 0.7f, -0.7f, 0.0f, //vertex 1 of triangle 0.0f, 0.0f, 0.0f, //vertex 2 of triangle }; static const GLfloat color_buffer_data1[] = { 1.0f, 0.0f, 0.0f, //color of vertex 0 1.0f, 0.0f, 0.0f, //color of vertex 1 1.0f, 0.0f, 0.0f, //color of vertex 2 1.0f, 0.0f, 0.0f, //color of vertex 0 1.0f, 0.0f, 0.0f, //color of vertex 1 1.0f, 0.0f, 0.0f, //color of vertex 2 1.0f, 0.0f, 0.0f, //color of vertex 0 1.0f, 0.0f, 0.0f, //color of vertex 1 1.0f, 0.0f, 0.0f, //color of vertex 2 1.0f, 0.0f, 0.0f, //color of vertex 0 1.0f, 0.0f, 0.0f, //color of vertex 1 1.0f, 0.0f, 0.0f, //color of vertex 2 1.0f, 0.0f, 0.0f, //color of vertex 0 1.0f, 0.0f, 0.0f, //color of vertex 1 1.0f, 0.0f, 0.0f, //color of vertex 2 1.0f, 0.0f, 0.0f, //color of vertex 0 1.0f, 0.0f, 0.0f, //color of vertex 1 1.0f, 0.0f, 0.0f, //color of vertex 2 1.0f, 0.0f, 0.0f, //color of vertex 2 1.0f, 0.0f, 0.0f, //color of vertex 0 1.0f, 0.0f, 0.0f, //color of vertex 1 1.0f, 0.0f, 0.0f, //color of vertex 2 1.0f, 0.0f, 0.0f, //color of vertex 2 1.0f, 0.0f, 0.0f, //color of vertex 0 1.0f, 0.0f, 0.0f, //color of vertex 1 1.0f, 0.0f, 0.0f, //color of vertex 2 }; glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer[GEO_TRIANGLE_2]); //Pass vertex/color data to the GPU at load time (not run time) glBufferData(GL_ARRAY_BUFFER, sizeof(color_buffer_data1), color_buffer_data1, GL_STATIC_DRAW); //Set the current active buffer glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[GEO_TRIANGLE_2]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data1), vertex_buffer_data1, GL_STATIC_DRAW); //Load vertex and fragment shaders //Colors m_programID = LoadShaders( //Vertex shader for position "Shader//SimpleVertexShader.vertexshader", //Fragment shader for color "Shader//SimpleFragmentShader.fragmentshader"); //Use our shader glUseProgram(m_programID); }