void jointToWorldTest() { Joint j0, j1, j2; // J0 Setup j0.name = "J0"; j0.parentIndex = -1; j0.position = vec3(0, 0, 0); j0.orientation = quat(1, 0, 0, 0); // Identity quaternion // J1 Setup j1.name = "J1"; j1.parentIndex = 0; j1.position.x = 70.1f; j1.position.y = 70.1f; j1.orientation = glm::quat_cast(glm::rotate(mat4(), 45.0f, vec3(0, 0, 1))); j2.name = "J2"; j2.parentIndex = 1; //j2.position.x = 70.1f; j2.position.x = 0; j2.position.y = 100.0f; //j2.orientation = glm::quat_cast(glm::rotate(mat4(), 45.0f, vec3(0, 0, 1))); Skeleton skeleton; skeleton.joints.push_back(j0); skeleton.joints.push_back(j1); skeleton.joints.push_back(j2); buildJointToWorldMatrices(skeleton); //mat4 worldM = jointToWorld(skeleton, j2); //cout << "World coordinate: " << worldM[3][0] << ", " << worldM[3][1] << ", " << worldM[3][2] << endl; }
Camera& Camera::stereo(float _c, float _e) { isStereo = true; _convergence = _c; _eyeSep = _e; float top, bottom, leftL, rightL, leftR, rightR; top = nearPlane * tan(radians(fovy)/2); bottom = -top; float a = aspect * tan(radians(fovy)/2) * convergence(); float b = a - eyeSep()/2; float c = a + eyeSep()/2; leftR = -c * nearPlane/convergence(); rightR = b * nearPlane/convergence(); leftL = -b * nearPlane/convergence(); rightL = c * nearPlane/convergence(); //rightProjection = Matrix4f::perspective(leftR, rightR, bottom, top, nearPlane, farPlane ); //rightTranslate = Matrix4f::translate( -eyeSep/2, 0.0f, 0.0f ); //leftProjection = Matrix4f::perspective(leftL, rightL, bottom, top, nearPlane, farPlane ); //leftTranslate = Matrix4f::translate( eyeSep/2, 0.0f, 0.0f ); rightProjection = glm::frustum(leftR, rightR, bottom, top, nearPlane, farPlane ); rightTranslate = glm::translate(mat4(1.0), vec3(-eyeSep()/2, 0.0f, 0.0f) ); leftProjection = glm::frustum(leftL, rightL, bottom, top, nearPlane, farPlane ); leftTranslate = glm::translate(mat4(1.0), vec3(eyeSep()/2, 0.0f, 0.0f) ); isTransformed = true; return *this; }
void GLWidget::resizeGL(int w, int h) { width = w; height = h; radius = min(width, height) * .75; float aspect = (float)w/h; projMatrix = perspective(45.0f, aspect, 1.0f, 100.0f); viewMatrix = lookAt(vec3(0,0,-10),vec3(0,0,0),vec3(0,1,0)); modelMatrix = mat4(1.0f); glUseProgram(cubeProg); glUniformMatrix4fv(cubeProjMatrixLoc, 1, false, value_ptr(projMatrix)); glUniformMatrix4fv(cubeViewMatrixLoc, 1, false, value_ptr(viewMatrix)); glUniformMatrix4fv(cubeModelMatrixLoc, 1, false, value_ptr(modelMatrix)); glUniformMatrix4fv(cubeRotationMatrixLoc, 1, false, value_ptr(rotationMatrix)); glUseProgram(gridProg); glUniformMatrix4fv(gridProjMatrixLoc, 1, false, value_ptr(projMatrix)); glUniformMatrix4fv(gridViewMatrixLoc, 1, false, value_ptr(viewMatrix)); glUniformMatrix4fv(gridModelMatrixLoc, 1, false, value_ptr(modelMatrix)); glUniformMatrix4fv(gridRotationMatrixLoc, 1, false, value_ptr(rotationMatrix)); }
void ParticlesFire::InitScene() { CompileAndLinkShaders(); GLuint shaderHandle = _shader.GetHandle(); _renderSub = glGetSubroutineIndex(shaderHandle, GL_VERTEX_SHADER, "render"); _updateSub = glGetSubroutineIndex(shaderHandle, GL_VERTEX_SHADER, "update"); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glPointSize(50.0f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); _projection = mat4(1.0); _model = mat4(1.0f); _angle = glm::half_pi<float>(); InitBuffers(); const char* texName = "./media/texture/fire.bmp"; glActiveTexture(GL_TEXTURE0); BMPReader::loadTex(texName); _shader.SetUniform("ParticleTex", 0); _shader.SetUniform("ParticleLifetime", 4.0f); _shader.SetUniform("Accel", vec3(0.0f, 0.1f, 0.0f)); SetMatrices(); }
void OrthoCamera::updateMatrices() { vec3 s = glm::normalize(glm::cross(direction, upVector)); vec3 u = glm::normalize(glm::cross(s, direction)); mat4 untranslatedViewMatrix = mat4(vec4(s, 0), vec4(u, 0), vec4(direction, 0), vec4(0, 0, 0, 1.0f)); untranslatedViewMatrix = glm::transpose(untranslatedViewMatrix); viewMatrix = glm::translate(untranslatedViewMatrix, -focus); projectionMatrix = mat4(1/width, 0, 0, 0, 0, 1/height, 0, 0, 0, 0, 1/depth, 0, 0, 0, 0, 1); }
void Scene::draw() { glClearColor(0.1f, 0.1f, 0.1f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 mv; // Draw the particle system mv = _view * _modelTrans * _modelRot; glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); _psProg->bind(); _psProg->setUniform("mv", mv); _psProg->setUniform("proj", _proj); _particleSystemView->draw(); glDisable(GL_BLEND); #if 0 // Draw the settings icon _tqProg->bind(); _tqProg->setUniform("mv", _settingsIconModel); _tqProg->setUniform("proj", mat4()); _settingsIcon->draw(); _tqProg->release(); #endif }
void GLWidget::mouseMoveEvent(QMouseEvent *event) { last.x = event->x(); last.y = event->y(); vec3 begin = pointOnVirtualTrackball(first); vec3 end = pointOnVirtualTrackball(last); float dotProduct = dot(normalize(begin), normalize(end)); float angle = acos(dotProduct); vec3 crossP = cross(begin, end); if(length(crossP) > .00001f) { rotationMatrix = rotate(mat4(1.0), angle, normalize(crossP)) * rotationMatrix; glUseProgram(cubeProg); glUniformMatrix4fv(cubeRotationMatrixLoc, 1, false, value_ptr(rotationMatrix)); glUseProgram(gridProg); glUniformMatrix4fv(gridRotationMatrixLoc, 1, false, value_ptr(rotationMatrix)); update(); } first.x = last.x; first.y = last.y; }
mat4 getChildToParentMatrix(const Joint &joint) { mat4 rotM(glm::mat4_cast(joint.orientation)); mat4 transM = glm::translate(mat4(1.0f), joint.position); return transM * rotM; //return rotM * transM; }
//---------------------------------------------------------------------------------------- TEST_F(Camera_Test, test_lookAt_forward) { vec3 eye(0.0f, 0.0f, 0.0f); vec3 center(0.0f, 0.0f, -1.0f); vec3 up(0.0f, 1.0f, 0.0f); camera.lookAt(eye, center, up); EXPECT_PRED2(mat4_eq, mat4(), camera.getViewMatrix()); }
void renderScene(void) { bool bRet; angle+=0.01; glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // glLightfv(GL_LIGHT0, GL_POSITION, lpos); vec4 Position = vec4( 0.0f, 0.0f, -1.0f, 1.0f ); mat4 ViewMatrix = glm::lookAt( vec3(0.0,0.0,-2.0), vec3(0.0,0.0,0.0), vec3(0.0,1.0,0.0) ); mat4 Model = mat4(1.0f); mat4 ModelMatrix = glm::rotate( Model, angle, vec3( 0.0f, 1.0f, 0.7f ) ); mat4 ModelViewMatrix = ViewMatrix * ModelMatrix; mat4 ProjectionMatrix = glm::perspective( 90.0f, 1.0f, 0.1f, 100.0f ); mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; mat3 NormalMatrix = glm::inverse( glm::transpose( glm::mat3(ModelViewMatrix) ) ); bRet = _GLSLProgram->SetUniform( "MVP", (mat4 const) MVP ); bRet = _GLSLProgram->SetUniform( "ProjectionMatrix", (mat4 const) ProjectionMatrix ); bRet = _GLSLProgram->SetUniform( "ModelViewMatrix", (mat4 const) ModelViewMatrix ); bRet = _GLSLProgram->SetUniform( "NormalMatrix", (mat3 const) NormalMatrix ); vec3 LightLa = vec3( 0.3, 0.3, 0.3 ); vec3 LightLd = vec3( 0.5, 0.5, 0.5 ); vec3 LightLs = vec3( 0.2, 0.2, 0.2 ); bRet = _GLSLProgram->SetUniform( "Light.La", LightLa ); bRet = _GLSLProgram->SetUniform( "Light.Ld", LightLd ); bRet = _GLSLProgram->SetUniform( "Light.Ls", LightLs ); vec3 LightPosition( 1.0f, 1.0f, -1.0f ); bRet = _GLSLProgram->SetUniform( "Light.Position", LightPosition ); vec3 MaterialCoeffKa( 1.0f, 1.0f, 1.0f ); vec3 MaterialCoeffKd( 1.0f, 1.0f, 1.0f ); vec3 MaterialCoeffKs( 1.0f, 1.0f, 1.0f ); bRet = _GLSLProgram->SetUniform( "Material.Ka", MaterialCoeffKa ); bRet = _GLSLProgram->SetUniform( "Material.Kd", MaterialCoeffKd ); bRet = _GLSLProgram->SetUniform( "Material.Ks", MaterialCoeffKs ); bRet = _GLSLProgram->SetUniform( "Material.Shininess", 1.0f ); _GLSLProgram->BindVertexArray(); glDrawArrays( GL_TRIANGLES, 0, 3 ); // glFrontFace(GL_CW); // glutSolidTeapot( 10 ); // glFrontFace(GL_CCW); _GLSLProgram->UnBindVertexArray(); glutSwapBuffers(); }
void Decay::DrawScene() { _model = mat4(1.0f); _model = glm::rotate(_model, glm::radians(-15.0f), vec3(0.0f, 1.0f, 0.0f)); _model = glm::rotate(_model, glm::radians(-90.0f), vec3(1.0f, 0.0f, 0.0f)); SetMatrices(); _shader.SetUniform("Material.Kd", 0.7f, 0.5f, 0.3f); _shader.SetUniform("Material.Ks", 1.0f, 1.0f, 1.0f); _shader.SetUniform("Material.Shininess", 100.0f); _teapot->Render(); }
Camera& Camera::transform() { mat4 rM = mat4( rightVec.x, upVec.x, viewVec.x, 0, rightVec.y, upVec.y, viewVec.y, 0, rightVec.z, upVec.z, viewVec.z, 0, 0,0,0,1); mat4 tM = glm::translate( mat4(1.0), vec3(posVec.x, posVec.y, posVec.z) ); view = rM * tM; if (isFrontBack) { mat4 rrM = mat4( -rightVec.x, upVec.x, -viewVec.x, 0, -rightVec.y, upVec.y, -viewVec.y, 0, -rightVec.z, upVec.z, -viewVec.z, 0, 0,0,0,1); backView = rrM * tM; } if (isStereo) { //printf("isStereo = TRUE\n"); rightView = rightTranslate * view; leftView = leftTranslate * view; if (isFrontBack) { rightBackView = rightTranslate * backView; leftBackView = leftTranslate * backView; } } isTransformed = false; return *this; }
void Scene::setProjection() { _proj = glm::perspective(_fov, float(_width) / float(_height), _depthMin, _depthMax); glViewport(0, 0, _width, _height); // Set the size for the settings quad float size = 0.03; float qWidth = size; float aspectRatio = float(_width) / float(_height); float qHeight = size * aspectRatio; float qTransX = 1.0 - qWidth - size * 0.5; float qTransY = -1.0 + qHeight + size * 0.5; mat4 qScale = glm::scale(mat4(), vec3(qWidth, qHeight, 1.0)); mat4 qTrans = glm::translate(mat4(), vec3(qTransX, qTransY, 0)); _settingsIconModel = qTrans * qScale; qScale = glm::scale(mat4(), vec3(1.0 / qWidth, 1.0 / qHeight, 1.0)); qTrans = glm::translate(mat4(), vec3(-qTransX, -qTransY, 1.0)); _settingsIconModelInv = qScale * qTrans; }
void childToParentTest() { Skeleton skeleton; Joint j0; j0.name = "J0"; j0.parentIndex = -1; j0.position = vec3(70.71, 70.71, 0); j0.orientation = glm::quat_cast(glm::rotate(mat4(), 45.0f, vec3(0, 0, 1))); skeleton.joints.push_back(j0); mat4 P = getChildToParentMatrix(j0) ; printMatrix(P); vec4 v(0,100, 0, 1); // Make it homogenous with w = 1 vec4 v_ = P * v; cout << "In world space: " << v_.x << ", " << v_.y << ", " << v_.z << endl; }
void My_OpenGLWidget::resizeGL(int width, int height) { glViewport(0, 0, width, height); float aspectRatio = static_cast<float>(width) / static_cast<float>(height); //top, bottom, near, and far are still ok, aspect ratio is the problem float bottom = -1.0f; float nearZ = 2.0f; float top = nearZ * tan(3.14/8.0f); float farZ = -1.0f; float right = aspectRatio; float left = -aspectRatio; //near and far had namespace collisions //mat4 projectionScale = mat4(vec4(2.0f / (right - left), 0.0f, 0.0f, 0.0f), vec4(0.0f, 2.0f / (top - bottom), 0.0f, 0.0f), vec4(0.0f, 0.0f, 2.0f / (farZ - nearZ), 0.0f), vec4(0.0f, 0.0f, 0.0f, 1.0f)); mat4 projectionScale = mat4(vec4((nearZ/right), 0, 0, 0), vec4(0, (nearZ/top), 0,0), vec4(0,0,((-farZ+nearZ)/(farZ-nearZ)),((-2*farZ*nearZ)/(farZ-nearZ))), vec4(0,0,-1, 0)); //mat4 projectionTranslate = glm::translate(vec3(0.0f, 0.0f, 1.0f)); //projectionMatrix = projectionScale * projectionTranslate; projectionMatrix = projectionScale; }
void buildJointToWorldMatrices(Skeleton &skeleton) { for(int i = 0; i < skeleton.joints.size(); ++i) { Joint &joint = skeleton.joints[i]; glm::mat4 rotM = glm::mat4_cast(joint.orientation); glm::mat4 transM = glm::translate(mat4(1.0f), joint.position); mat4 toParentM = transM * rotM; if(i == 0) { joint.jointToWorld = toParentM; } else { const Joint &parent = skeleton.joints[joint.parentIndex]; joint.jointToWorld = parent.jointToWorld * toParentM; } cout << joint.name << " to model: " << endl; printMatrix(joint.jointToWorld); } }
void Decay::InitScene() { CompileAndLinkShader(); glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glEnable(GL_DEPTH_TEST); _shader.Use(); _shader.SetUniform("NoiseTex", 0); GLuint noiseTex = NoiseTex::Generate2DTex(10.0f); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, noiseTex); _teapot = new Teapot(14, mat4(1.0f)); _shader.SetUniform("Light.Intensity", vec3(1.0f, 1.0f, 1.0f)); _lightPos = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); _shader.SetUniform("LowThreshold", 0.45f); _shader.SetUniform("HighThreshold", 0.65f); }
void Scene::tapGesture(float x, float y) { #if 0 vec4 pos(x, y, 0, 1); mat4 bias = glm::translate(mat4(), vec3(-1, 1, 0)); #endif #if 0 // Check to see if the settings icon was clicked mat4 scaleAndBias = glm::scale(bias, vec3(2.0 / _width, -2.0 / _height, 1.0)); // Check to see if the settings icon was clicked pos = _settingsIconModelInv * scaleAndBias * pos; if(pos.x >= -1.0 && pos.x <= 1.0 && pos.y >= -1.0 && pos.y <= 1.0) { _settingsTapped = true; std::cerr << "tapped settings" << std::endl; } #endif }
void QuatCam::CalculateRotation(const double a_dt, glm::vec3 a_aircraftAxis) { // Calculate the rotation of the delta vector glm::quat key_quat = glm::quat(a_aircraftAxis); //if (glm::length(a_aircraftAxis) > 0.01f) m_camera_quat = key_quat * m_camera_quat; m_camera_quat = glm::normalize(m_camera_quat); glm::mat4 rotate = glm::mat4_cast(m_camera_quat); glm::mat4 translate = glm::mat4(1.0f); translate = glm::translate(translate, -glm::vec3(m_worldTrans[1])); m_viewTrans = rotate * translate; SetWorldTrans(m_worldTrans * mat4(glm::normalize(key_quat))); //mat3 xRot = mat3(rotate((float)(a_cursorDelta.x * (a_dt * -m_rotSpeed)), vec3(0, 1, 0))); //mat3 yRot = mat3(rotate((float)(a_cursorDelta.y * (a_dt * -m_rotSpeed)), vec3(1, 0, 0))); // //// Make sure the magnitude is larger than 0 (divide by 0 error) //if (length(a_cursorDelta) > 0.01f) // SetWorldTrans(m_worldTrans * mat4(xRot * yRot)); // //// Create a side vector and then from that an up vector //vec3 m_sideVector = cross(vec3(0, 1, 0), vec3(m_worldTrans[2])); //vec3 m_upVector = cross(m_sideVector, vec3(m_worldTrans[2])); // //// Normalise the two //m_sideVector = normalize(m_sideVector); //m_upVector = normalize(m_upVector); // //// Apply to the world Transform //m_worldTrans[0] = vec4(m_sideVector, 0); //m_worldTrans[1] = vec4(-m_upVector, 0); //m_worldTrans[2] = normalize(m_worldTrans[2]); //// Apply View Transform //m_viewTrans = glm::inverse(m_worldTrans); }
void setViewFP() { using namespace glm; glm::mat4 Vinv(1.0); // right-left rotate Vinv = glm::rotate(glm::mat4(1.0), g_CamangleY, glm::vec3(0.0f, 1, 0)); Vinv = glm::rotate(Vinv, g_CamangleX, glm::vec3(1, 0, 0)); // get lookat vec vec4 t = Vinv * vec4(0, 0, -1, 1); g_lookAt.x = t.x; g_lookAt.y = t.y; g_lookAt.z = t.z; // S is translation with respect to Cam glm::mat4 S = glm::translate(glm::mat4(1.0), glm::vec3(g_CamDx, g_CamDy, g_CamDz)); glm::mat4 V = glm::inverse(Vinv); // S with respect to World vec4 camPos4f = vec4(g_CamPos.x, g_CamPos.y, g_CamPos.z, 1.0f); camPos4f = Vinv * S * V * camPos4f; g_CamPos.x = camPos4f.x; // == No player y movement g_CamPos.y = camPos4f.y; g_CamPos.z = camPos4f.z; // printf("g_CamPos: %f, %f, %f\n", g_CamPos.x, g_CamPos.y, g_CamPos.z); // xlate camera in world Vinv = translate(mat4(1), g_CamPos) * Vinv; //g_CamDz = g_CamDx = 0; g_view = inverse(Vinv); }
void FilmCamera::updateMatrices() { // view matrix untranslatedViewMatrix = glm::toMat4(getOrientation()); viewMatrix = translate(untranslatedViewMatrix, -position); // projection matrix aspectRatio = (float)getFrameWidth() / (float)getFrameHeight(); float extendedAOV = (atan(tan(angleOfView / 2) * (((float)width + 2 * horizontalMargin) / width))) * 2; // as found in hearn & baker float x0 = 1.0f/(tan(extendedAOV/2.0f)); float y1 = (1.0f/(tan(extendedAOV/2.0f))) * aspectRatio; float z2 = (nearPlane + farPlane)/(nearPlane - farPlane); float w2 = -1.0f; float z3 = (-2.0f * nearPlane * farPlane)/(nearPlane - farPlane); projectionMatrix = mat4(x0, 0, 0, 0, 0, y1, 0, 0, 0, 0, z2, w2, 0, 0, z3, 0); }
// TODO rounder! void DisplayCanvas::renderIndicators() { // Bind the program and VAO GLuint program = indicator_object_.program; glUseProgram(program); glBindVertexArray(indicator_object_.vao); // Set up view-projection matrix mat4 vp = proj_ * view_; GLuint vp_loc = glGetUniformLocation(program, "VP"); glUniformMatrix4fv(vp_loc, 1, false, glm::value_ptr(vp)); std::list< ::Move>::const_iterator it; for(it = selected_moves_.begin(); it != selected_moves_.end(); it++) { // Get the target square of the move int x = unmailboxX(it->target()); int y = unmailboxY(it->target()); int z = unmailboxZ(it->target()); // Compute model matrix vec3 corner = vec3(x - 4, y - 4, z - 4); mat4 model = glm::translate(mat4(), corner); // Set uniform variables GLuint m_loc = glGetUniformLocation(program, "M"); glUniformMatrix4fv(m_loc, 1, false, glm::value_ptr(model)); // Draw glDrawArrays(GL_TRIANGLES, 0, 3 * 8); } // Unbind everything glBindVertexArray(0); glUseProgram(0); }
// TODO delete the silly color things once you have real models void DisplayCanvas::renderPieces() { // Bind the program and VAO GLuint program = piece_object_.program; glUseProgram(program); glBindVertexArray(piece_object_.vao); // Set up view-projection matrix mat4 vp = proj_ * view_; GLuint vp_loc = glGetUniformLocation(program, "viewproject"); glUniformMatrix4fv(vp_loc, 1, false, glm::value_ptr(vp)); // Set up the light and eye locations (which are the same)! GLuint light_loc = glGetUniformLocation(program, "light"); GLuint eye_loc = glGetUniformLocation(program, "eye"); glUniform3f(light_loc, EYE_RAD * sin(phi_) * cos(theta_), EYE_RAD * sin(phi_) * sin(theta_), EYE_RAD * cos(phi_)); glUniform3f(eye_loc, EYE_RAD * sin(phi_) * cos(theta_), EYE_RAD * sin(phi_) * sin(theta_), EYE_RAD * cos(phi_)); // Iterates through the board for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { for(int k = 0; k < 8; k++) { // Find piece data Piece p = board_.getPiece(mailbox(i, j, k)); // Compute model matrix mat4 model; if(p.color() == WHITE) { vec3 corner = vec3(i - 3.5, j - 3.5, k - 4); model = glm::translate(mat4(), corner); glFrontFace(GL_CCW); } else { vec3 corner = vec3(i - 3.5, j - 3.5, k - 3); model = glm::translate(mat4(), corner); model[2][2] = -1; // flips it across z = 0 glFrontFace(GL_CW); } // Compute the normal matrix. glm::mat3 normMat = glm::transpose(glm::inverse(glm::mat3(model))); // Compute hue PieceType pt = p.type(); if(pt == NIL || pt == BORDER) continue; int tmp = (pt == W_PAWN) ? B_PAWN : pt; // Makes pawns match float hue = tmp * (360.0f / 13); vec3 color = glm::rgbColor(vec3(hue, 1, 1)); // Set uniform variables GLuint m_loc = glGetUniformLocation(program, "model"); GLuint n_loc = glGetUniformLocation(program, "normMat"); GLuint color_loc = glGetUniformLocation(program, "color"); glUniformMatrix4fv(m_loc, 1, false, glm::value_ptr(model)); glUniformMatrix3fv(n_loc, 1, false, glm::value_ptr(normMat)); glUniform3f(color_loc, color.r, color.g, color.b); // Find the piece model in the VBO and draw! int offset = piece_model_offset_[pt]; int length = piece_model_offset_[pt + 1] - offset; glDrawArrays(GL_TRIANGLES, offset, length); } } } // Unbind everything and reset the front face direction glFrontFace(GL_CCW); glBindVertexArray(0); glUseProgram(0); }
void display() { static float angle = 0.0; angle +=0.5; glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); shader->begin(); /// init shader data glm::vec3 eyePos = glm::vec3(4.0,0.0,0.0); // init light in the scene glm::vec3 lightPos = glm::vec3(0.0,1.0,2.0); vec3 La = vec3(0.9,0.9,0.9); vec3 Ld = vec3(1.0,1.0,1.0); vec3 Ls = vec3(1.0,1.0,1.0); // init model material vec3 Ka = vec3(0.2,0.2,0.2); vec3 Kd = vec3(1.0,1.0,1.0); vec3 Ks = vec3(1.0,1.0,1.0); float shiness = 5.0; glm::mat4 projection_matrix = glm::perspective(45.0f,(float)width/height,1.0f,1000.0f); glm::mat4 view_matrix = glm::lookAt(eyePos,glm::vec3(0.0),glm::vec3(0.0,1.0,0.0)); view_matrix = glm::rotate(view_matrix,xAngle,glm::vec3(0.0,1.0,0.0)); view_matrix = glm::rotate(view_matrix,yAngle,glm::vec3(1.0,0.0,0.0)); glm::mat4 model_matrix = glm::rotate(glm::mat4(1.0),0.0f,glm::vec3(0.0,1.0,0.0)); model_matrix = glm::translate(model_matrix,glm::vec3(0.0,0.0,0)); /// populate shader data to shader shader->setUniform("eyePos",eyePos); // for light shader->setUniform("light.position",lightPos); shader->setUniform("light.La",La); shader->setUniform("light.Ld",Ld); shader->setUniform("light.Ls",Ls); // for material shader->setUniform("mat.Ka",Ka); shader->setUniform("mat.Kd",Kd); shader->setUniform("mat.Ks",Ks); shader->setUniform("mat.shiness",shiness); shader->setUniform("view_matrix",view_matrix); shader->setUniform("projection_matrix",projection_matrix); shader->setUniform("model_matrix",model_matrix); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,brickTexID); shader->setUniform("brickTex",0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,mossTexID); shader->setUniform("mossTex",1); model->draw(); mat4 rotate_matrix = glm::rotate(mat4(1.0),angle,glm::vec3(1.0,1.0,0.0)); model_matrix = glm::translate(glm::mat4(1.0),mat3(rotate_matrix) * lightPos); shader->setUniform("light.position",mat3(rotate_matrix)*lightPos); shader->setUniform("model_matrix", model_matrix); glutWireSphere(0.2,10,10); glutSwapBuffers(); }
int main(int argc, char** argv) { setup_context(); polygon_mode = 2; vector<vec3> line_verts; for (int i=0, j=-FLOOR_SIZE/2; i < 11; ++i, j+=FLOOR_SIZE/10) { line_verts.push_back(vec3(j, -1, -FLOOR_SIZE/2)); line_verts.push_back(vec3(j, -1, FLOOR_SIZE/2)); line_verts.push_back(vec3(-FLOOR_SIZE/2, -1, j)); line_verts.push_back(vec3(FLOOR_SIZE/2, -1, j)); } GLuint line_vao, line_buf; glGenVertexArrays(1, &line_vao); glBindVertexArray(line_vao); glGenBuffers(1, &line_buf); glBindBuffer(GL_ARRAY_BUFFER, line_buf); glBufferData(GL_ARRAY_BUFFER, line_verts.size()*3*sizeof(float), &line_verts[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); Mesh torus; Mesh sphere; generate_torus(torus.verts, torus.tris, torus.texcoords, 0.3, 0.1, 40, 20); generate_sphere(sphere.verts, sphere.tris, sphere.texcoords, 0.1, 26, 13); compute_normals(torus.verts, torus.tris, NULL, DEG_TO_RAD(30), torus.normals); compute_normals(sphere.verts, sphere.tris, NULL, DEG_TO_RAD(30), sphere.normals); vector<vert_attribs> vert_data; int v; for (int i=0, j=0; i<torus.tris.size(); ++i, j+=3) { v = torus.tris[i].x; vert_data.push_back(vert_attribs(torus.verts[v], torus.normals[j])); v = torus.tris[i].y; vert_data.push_back(vert_attribs(torus.verts[v], torus.normals[j+1])); v = torus.tris[i].z; vert_data.push_back(vert_attribs(torus.verts[v], torus.normals[j+2])); } for (int i=0, j=0; i<sphere.tris.size(); ++i, j+=3) { v = sphere.tris[i].x; vert_data.push_back(vert_attribs(sphere.verts[v], sphere.normals[j])); v = sphere.tris[i].y; vert_data.push_back(vert_attribs(sphere.verts[v], sphere.normals[j+1])); v = sphere.tris[i].z; vert_data.push_back(vert_attribs(sphere.verts[v], sphere.normals[j+2])); } #define NUM_SPHERES 50 vector<vec3> instance_pos; vec2 rand_pos; for (int i=0; i<NUM_SPHERES+1; ++i) { rand_pos = glm::diskRand(FLOOR_SIZE/2.0f); if (i) instance_pos.push_back(vec3(rand_pos.x, 0.4, rand_pos.y)); else instance_pos.push_back(vec3()); } GLuint vao, buffer; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); size_t total_size = (torus.tris.size()*3 + sphere.tris.size()*3) * sizeof(vert_attribs); size_t sphere_offset = torus.tris.size()*3; glBufferData(GL_ARRAY_BUFFER, total_size, &vert_data[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vert_attribs), 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vert_attribs), (void*)sizeof(vec3)); GLuint inst_buf; glGenBuffers(1, &inst_buf); glBindBuffer(GL_ARRAY_BUFFER, inst_buf); glBufferData(GL_ARRAY_BUFFER, instance_pos.size()*3*sizeof(float), &instance_pos[0], GL_STATIC_DRAW); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribDivisor(3, 1); GLuint basic_shader = load_shader_file_pair("../media/shaders/basic_transform.vp", "../media/shaders/uniform_color.fp"); GLuint gouraud_shader = load_shader_file_pair("../media/shaders/gouraud_ads.vp", "../media/shaders/gouraud_ads.fp"); GLuint phong_shader = load_shader_file_pair("../media/shaders/phong_ads.vp", "../media/shaders/phong_ads.fp"); mat4 proj_mat = glm::perspective(DEG_TO_RAD(35.0f), WIDTH/(float)HEIGHT, 0.3f, 100.0f); mat4 view_mat; mat4 mvp_mat; mat3 normal_mat; mat4 translate_sphere = glm::translate(mat4(1), vec3(0.8f, 0.4f, 0.0f)); vec4 floor_color(0, 1, 0, 1); vec3 torus_ambient(0.0, 0, 0); vec3 torus_diffuse(1.0, 0, 0); vec3 torus_specular(0, 0, 0); vec3 sphere_ambient(0, 0, 0.2); vec3 sphere_diffuse(0, 0, 0.7); vec3 sphere_specular(1, 1, 1); glUseProgram(basic_shader); set_uniform4fv(basic_shader, "color", glm::value_ptr(floor_color)); glUseProgram(gouraud_shader); glUseProgram(phong_shader); set_uniform1f(phong_shader, "shininess", 128.0f); vec3 light_direction(0, 10, 5); glUseProgram(basic_shader); GLFrame camera(true); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); SDL_SetRelativeMouseMode(SDL_TRUE); unsigned int old_time = 0, new_time=0, counter = 0, last_time = SDL_GetTicks(); float total_time; while (1) { new_time = SDL_GetTicks(); if (handle_events(camera, last_time, new_time)) break; last_time = new_time; total_time = new_time/1000.0f; if (new_time - old_time > 3000) { printf("%f FPS\n", counter*1000.f/(new_time-old_time)); old_time = new_time; counter = 0; } glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); view_mat = camera.get_camera_matrix(); mvp_mat = proj_mat * view_mat; glUseProgram(basic_shader); set_uniform_mat4f(basic_shader, "mvp_mat", glm::value_ptr(mvp_mat)); glBindVertexArray(line_vao); glDrawArrays(GL_LINES, 0, line_verts.size()); glBindVertexArray(vao); glUseProgram(phong_shader); vec3 light_dir = mat3(view_mat)*light_direction; set_uniform3fv(phong_shader, "light_direction", glm::value_ptr(light_dir)); set_uniform_mat4f(phong_shader, "mvp_mat", glm::value_ptr(mvp_mat)); normal_mat = mat3(view_mat); set_uniform_mat3f(phong_shader, "normal_mat", glm::value_ptr(normal_mat)); set_uniform3fv(phong_shader, "ambient_color", glm::value_ptr(sphere_ambient)); set_uniform3fv(phong_shader, "diffuse_color", glm::value_ptr(sphere_diffuse)); set_uniform3fv(phong_shader, "spec_color", glm::value_ptr(sphere_specular)); glDrawArraysInstancedBaseInstance(GL_TRIANGLES, torus.tris.size()*3, sphere.tris.size()*3, NUM_SPHERES, 1); mat4 rot_mat = glm::rotate(mat4(1), -1*total_time*DEG_TO_RAD(60.0f), vec3(0, 1, 0)); mvp_mat = mvp_mat * rot_mat * translate_sphere; normal_mat = mat3(view_mat*rot_mat); set_uniform_mat3f(phong_shader, "normal_mat", glm::value_ptr(normal_mat)); set_uniform_mat4f(phong_shader, "mvp_mat", glm::value_ptr(mvp_mat)); glDrawArrays(GL_TRIANGLES, torus.tris.size()*3, sphere.tris.size()*3); //draw rotating torus mvp_mat = proj_mat * view_mat; rot_mat = glm::rotate(mat4(1), total_time*DEG_TO_RAD(60.0f), vec3(0, 1, 0)); mvp_mat = mvp_mat * rot_mat; set_uniform_mat4f(phong_shader, "mvp_mat", glm::value_ptr(mvp_mat)); normal_mat = mat3(view_mat*rot_mat); set_uniform_mat3f(phong_shader, "normal_mat", glm::value_ptr(normal_mat)); set_uniform3fv(phong_shader, "ambient_color", glm::value_ptr(torus_ambient)); set_uniform3fv(phong_shader, "diffuse_color", glm::value_ptr(torus_diffuse)); set_uniform3fv(phong_shader, "spec_color", glm::value_ptr(torus_specular)); glDrawArrays(GL_TRIANGLES, 0, torus.tris.size()*3); SDL_GL_SwapWindow(window); last_time = new_time; ++counter; } glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &buffer); glDeleteProgram(basic_shader); cleanup(); return 0; }
int main(int argc, char** argv) { /* Initialize logging. */ START_EASYLOGGINGPP(argc, argv); LOG(TRACE) << "Logging initialized."; /* Initialize SDL. */ LOG(TRACE) << "Initializing SDL..."; int result = SDL_Init(SDL_INIT_VIDEO); if (result != 0) { LOG(FATAL) << "Could not initialize SDL: " << SDL_GetError(); } window = SDL_CreateWindow(argv[0], 0, 0, (int)window_width, (int)window_height, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); if (window == nullptr) { LOG(FATAL) << "Could not create window: " << SDL_GetError(); } SDL_ShowCursor(SDL_DISABLE); SDL_SetRelativeMouseMode(SDL_TRUE); frequency = SDL_GetPerformanceFrequency(); time_last_frame = SDL_GetPerformanceCounter(); LOG(INFO) << "Performance counter frequency: " << frequency; /* Initialize OpenGL. */ LOG(TRACE) << "Initializing OpenGL..."; SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GLContext gl_context = SDL_GL_CreateContext(window); if (gl_context == nullptr) { LOG(FATAL) << SDL_GetError(); } glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { LOG(FATAL) << "Could not initialize GLEW: " << glewGetErrorString(glewError); } glEnable(GL_BLEND); glEnable(GL_DEPTH_TEST); glEnable(GL_VERTEX_ARRAY); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); /* Load assets. */ LOG(TRACE) << "Loading assets..."; shaders = new ShaderManager(); { shader_terrain = shaders->get("terrain"); shader_terrain->apply(); glActiveTexture(GL_TEXTURE0); texture_terrain = new Texture("terrain"); shader_terrain->updateUniform("tex", 0); terrain = new Terrain("heightmap.png"); shader_terrain->updateUniform("max_height", terrain->getMaxHeight()); auto world = mat4(); world = translate(world, vec3(-terrain->getWidth() / 2.f, -terrain->getMaxHeight() / 2.f, -terrain->getDepth() / 2.f)); shader_terrain->updateUniform("K_a", 0.1f); shader_terrain->updateUniform("K_d", 0.9f); shader_terrain->updateWorldMatrix(world); LOG(INFO) << "Maximum terrain height: " << terrain->getMaxHeight(); LOG(INFO) << "Terrain width: " << terrain->getWidth(); LOG(INFO) << "Terrain depth: " << terrain->getDepth(); } { shader_skybox = shaders->get("skybox"); shader_skybox->apply(); glActiveTexture(GL_TEXTURE2); environment_map = new CubeMap("terrain_"); shader_skybox->updateUniform("cubeMap", 2); auto world = mat4(); world = scale(world, vec3(terrain->getWidth(), terrain->getWidth(), terrain->getDepth())); skybox = new Cube(); shader_terrain->apply(); shader_skybox->updateWorldMatrix(world); } { auto world = mat4(); world = scale(world, vec3(terrain->getWidth() / 2.f, terrain->getMaxHeight() * 2.f, terrain->getDepth() / 2.f)); shader_colour = shaders->get("colour"); shader_colour->apply(); shader_colour->updateWorldMatrix(world); origin = new Origin(); } { auto world = mat4(); world = translate(world, vec3(-terrain->getWidth() / 2.f, -terrain->getMaxHeight() / 2.f + 25.f, -terrain->getDepth() / 2.f)); shader_water = shaders->get("water"); shader_water->apply(); shader_water->updateUniform("K_a", 0.1f); shader_water->updateUniform("K_d", 0.0f); shader_water->updateUniform("K_s", 0.9f); shader_water->updateWorldMatrix(world); water = new Grid(terrain->getDepth(), 1000.f); } /* Set up light. */ auto light = Camera(); light.eye = vec3(1024.0f, 1024.f, 1024.f); light.at = vec3(0.0f, 0.0f, 0.0f); light.up = vec3(0.0f, 0.0f, -1.0f); auto light_dir = normalize(vec3(0.f, 0.25f, -1.f)); shader_terrain->apply(); shader_terrain->updateUniform("light_dir", light_dir); shader_water->apply(); shader_water->updateUniform("light_dir", light_dir); /* Set up view. */ auto camera = Camera(); auto camera_height = terrain->getMaxHeight() * 3.f; camera.eye = glm::vec3(0.f, camera_height, -terrain->getDepth() / 2.f); camera.at = glm::vec3(0, 0, 0); camera.up = glm::vec3(0, 1, 0); auto view = glm::lookAt(camera.eye, camera.at, camera.up); shaders->updateViewMatrices(view); /* Set up projection. */ auto proj = glm::perspective(45.f, window_width / window_height, 100.f, 25000.f); shaders->updateProjectionMatrices(proj); /* Set up frame buffers. */ frame_buffer_color = new ColorFrameBuffer(window_width, window_height); /* Main loop. */ float angle = 0.0f; bool done = false; SDL_Event event; LOG(TRACE) << "Entering main loop..."; while (!done) { while (SDL_PollEvent(&event) != 0) { if (event.type == SDL_QUIT) { done = true; } else if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_ESCAPE: LOG(INFO) << "Exiting normally at user request..."; done = true; break; case SDLK_PRINTSCREEN: LOG(INFO) << "Rendering screen shot..."; frame_buffer_color->bind(); draw(); frame_buffer_color->write(); frame_buffer_color->unbind(); break; default: break; } } else if (event.type == SDL_MOUSEMOTION) { const GLfloat X_SCALED = -(GLfloat)event.motion.xrel / window_width; const GLfloat Y_SCALED = -(GLfloat)event.motion.yrel / window_height; const GLfloat LEFT_RIGHT_ROT = X_SCALED * ANGLE_DELTA; const GLfloat UP_DOWN_ROT = Y_SCALED * ANGLE_DELTA; vec3 tempD(camera.at - camera.eye); vec4 d(tempD.x, tempD.y, tempD.z, 0.0f); vec3 right = cross(tempD, camera.up); mat4 rot; rot = rotate(rot, UP_DOWN_ROT, right); rot = rotate(rot, LEFT_RIGHT_ROT, camera.up); d = rot * d; camera.at.x = camera.eye.x + d.x; camera.at.y = camera.eye.y + d.y; camera.at.z = camera.eye.z + d.z; } } glm::vec3 direction = STEP * glm::normalize(camera.at - camera.eye); glm::vec3 right = STEP * glm::normalize(glm::cross(direction, camera.up)); auto keys = SDL_GetKeyboardState(nullptr); if (keys[SDL_SCANCODE_W]) { camera.eye += direction; camera.at += direction; } if (keys[SDL_SCANCODE_S]) { camera.eye -= direction; camera.at -= direction; } if (keys[SDL_SCANCODE_D]) { camera.eye += right; camera.at += right; } if (keys[SDL_SCANCODE_A]) { camera.eye -= right; camera.at -= right; } if (keys[SDL_SCANCODE_SPACE]) { camera.eye += STEP * camera.up; camera.at += STEP * camera.up; } if (keys[SDL_SCANCODE_LCTRL]) { camera.eye -= STEP * camera.up; camera.at -= STEP * camera.up; } view = glm::lookAt(camera.eye, camera.at, camera.up); shaders->updateViewMatrices(view); draw(); angle += 0.01f; } delete shaders; delete environment_map; delete frame_buffer_color; SDL_DestroyWindow(window); SDL_Quit(); return 0; }
int main() { //initialize the opengl window if (glfwInit() == false) return -1; GLFWwindow* window = glfwCreateWindow(1280, 720, "Computer Graphics", nullptr, nullptr); if (window == nullptr) { glfwTerminate(); return -2; } glfwMakeContextCurrent(window); //the rest of our code goes here! if (ogl_LoadFunctions() == ogl_LOAD_FAILED) { glfwDestroyWindow(window); glfwTerminate(); return -3; } //testing what version of OpenGL we are running auto major = ogl_GetMajorVersion(); auto minor = ogl_GetMinorVersion(); printf_s("GL: %i.%i\n", major, minor); //int imageWidth = 0, imageHeight = 0, imageFormat = 0; //unsigned char* data = stbi_load("crate.png", &imageWidth, &imageHeight, &imageFormat, STBI_default); //done initialize window and OpenGL //BEGIN SHADER SETUP string vshader = LoadShader("VertexShader.vert"); string fshader = LoadShader("FragmentShader.frag"); const char* vsSource = vshader.c_str(); const char* fsSource = fshader.c_str(); unsigned int vs = glCreateShader(GL_VERTEX_SHADER); unsigned int fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(vs, 1, (const char**)&vsSource, 0); glCompileShader(vs); glShaderSource(fs, 1, (const char**)&fsSource, 0); glCompileShader(fs); m_shader = glCreateProgram(); glAttachShader(m_shader, vs); glAttachShader(m_shader, fs); glBindAttribLocation(m_shader, 0, "Position"); glBindAttribLocation(m_shader, 1, "TexCoord"); glLinkProgram(m_shader); int success = GL_FALSE; glGetProgramiv(m_shader, GL_LINK_STATUS, &success); if (success == GL_FALSE) { int infoLogLength = 0; glGetShaderiv(m_shader, GL_INFO_LOG_LENGTH, &infoLogLength); char* infoLog = new char[infoLogLength]; glGetShaderInfoLog(m_shader, infoLogLength, 0, infoLog); printf("Error: Failed to link Gizmo shader program!\n%s\n", infoLog); delete[] infoLog; } //END SHADER SETUP int dims = 64; float *perlin_data = new float[dims * dims]; float scale = (1.0f / dims) * 3; for (int x = 0; x < 64; ++x) { for (int y = 0; y < 64; ++y) { perlin_data[y* dims + x] = glm::perlin(vec2(x, y) * scale) * 0.5f + 0.5f; } } //PLANE GENERATION int rows = 64; int cols = 64; // create opengl data for a grid Vertex* vertices = new Vertex[rows * cols]; for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { // offset position so that the terrain is centered vertices[r * cols + c].position = vec4(c - cols * 0.5f, 0, r - rows * 0.5f, 1); // setting up UVs vertices[r * cols + c].texCoord = vec2(c * (1.f / cols), r * (1.f / rows)); } } // keep track of number of indices for rendering int m_indexCount = (rows - 1) * (cols - 1) * 6; unsigned int* indices = new unsigned int[m_indexCount]; unsigned int index = 0; for (int r = 0; r < (rows - 1); ++r) { for (int c = 0; c < (cols - 1); ++c) { // triangle 1 indices[index++] = r * cols + c; indices[index++] = (r + 1) * cols + c; indices[index++] = (r + 1) * cols + (c + 1); // triangle 2 indices[index++] = r * cols + c; indices[index++] = (r + 1) * cols + (c + 1); indices[index++] = r * cols + (c + 1); } } //BUFFER GENERATION // generate buffers glGenBuffers(1, &m_VBO); glGenBuffers(1, &m_IBO); // generate vertex array object (descriptors) glGenVertexArrays(1, &m_VAO); // all changes will apply to this handle glBindVertexArray(m_VAO); // set vertex buffer data glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData( GL_ARRAY_BUFFER, //type of buffer to bind to (rows * cols) * sizeof(Vertex), //how large should the buffer be //in this example we have 64 * 64 elements //they are of size (Vertex) which is the size of a glm::vec4 and a glm::vec2 vertices, //the actual data GL_STATIC_DRAW); // index data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_indexCount * sizeof(unsigned int), indices, GL_STATIC_DRAW); // position glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); // texcoords glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(vec4)); // safety glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); /* In order to see our generated data, we are going to create a texture, fill it with the noise data, and display it on our quad*/ glGenTextures(1, &m_perlin_texture); glBindTexture(GL_TEXTURE_2D, m_perlin_texture); // bind data as float for a single channel glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, dims, dims, 0, GL_RED, GL_FLOAT, perlin_data); // enable blending else samples must be "exact" centre of texels glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // set wrap to stop errors at edge of noise sampling glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // unbind texture glBindTexture(GL_TEXTURE_2D, 0); //setup some matricesa mat4 m_model = mat4(); mat4 m_view = lookAt(vec3(120.0, 80.0, 120.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0)); mat4 m_projection = glm::perspective(glm::pi<float>()*0.25f, 16 / 9.f, 0.1f, 1000.f); mat4 m_projectionViewMatrix = m_projection * m_view; //end setup matrices unsigned int projectionViewUniform = glGetUniformLocation(m_shader, "ProjectionViewModel"); //start using shader... glUseProgram(m_shader); //because we are sending it to the uniform with this function glUniformMatrix4fv(projectionViewUniform, 1, false, value_ptr(m_projectionViewMatrix)); GLfloat height = glGetUniformLocation(m_shader, "heightScale"); int texUniform = glGetUniformLocation(m_shader, "noiseTexture"); glUniform1i(texUniform, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_perlin_texture); int i = 0; bool rise = true;; while (glfwWindowShouldClose(window) == false && glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS) { glClearColor(0.25f, 0.25f, 0.25f, 1); glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUniform1f(height, i); if (i >= dims) { rise = false; } else if (i <= -dims / 2) { rise = true; } if (rise == true) { i += 5; } else { i-=2; } unsigned int modelID = glGetUniformLocation(m_shader, "Model"); //float time = glfwGetTime(); //m_model = rotate(mat4(), 5.0f * cos(time), vec3(0, 1, 0)); glUniformMatrix4fv(modelID, 1, false, value_ptr(m_model)); glBindVertexArray(m_VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO); //draw glDrawElements(GL_TRIANGLES, m_indexCount, GL_UNSIGNED_INT, nullptr); //unbind glBindVertexArray(0); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); return 0; }
bool SceneGraph::InitializeGraph() { // Create objects // Add the objects into the actor map // Once an object is in the SceneGraph, object destruction is responsibility of the SceneGraph using AntiMatter::AppLog; using std::string; using std::vector; using glm::mat4; using glm::vec3; using glm::translate; using glm::rotate; // just calling to test the WavefrontObj parser // WavefrontObj j( g_Cfg.AssetsDir() + string("obj\\house\\house.obj") ); // Initialize the SceneLights collection (lights need access to the SceneGraph in order to initialize) // because of this, light initialization can't be done through plain old RAII if( ! m_lights.Initialize(this) ) { AppLog::Ref().LogMsg("SceneGraph lights failed to initialize"); return false; } // add lights to the scene graph typedef vector<Light*>::const_iterator CItr; const vector<Light*> lights = m_lights.Lights(); for( CItr n = lights.begin(); n != lights.end(); n ++ ) { Light* pLight = (*n); m_map.insert( ActorIdPair( pLight->Id(), pLight ) ); } mat4 tr; mat4 mW(1.0); // Terrain Terrain* pTerrain = new (std::nothrow) Terrain( this, &m_RootNode, string("terrain"), g_Cfg.AssetsDir() + string("heightfield4.bmp"), // height map g_Cfg.AssetsDir() + string("grassC.jpg"), // texture map (1 of n ?) g_Cfg.AssetsDir() + string("256-circle-alphamap.bmp"), // alphamap 128,128, 4.0f, 4.0f, 0.1f ); if( ! pTerrain || ! pTerrain->Initialized() ) { AppLog::Ref().LogMsg("SceneGraph failed to initialize Terrain"); return false; } m_map.insert( ActorIdPair( pTerrain->Id(), pTerrain) ); tr = translate( mat4(1.0), vec3(0, -275, 0) ); pTerrain->GetNodeData().W() *= tr; // Globe Globe* pGlobe = new (std::nothrow) Globe( this, &m_RootNode, std::string("globe"), 350.0f, 30, 30, string(""), glm::vec4(1.0, 1.0, 1.0, 0.8) ); // position the globe if( ! pGlobe || ! pGlobe->Initialized() ) { AppLog::Ref().LogMsg("SceneGraph failed to intialize the Globe"); return false; } tr = translate( glm::mat4(1.0), vec3(0, 0, 0) ); pGlobe->GetNodeData().W() *= tr; m_map.insert( ActorIdPair( pGlobe->Id(), pGlobe) ); // snow Snow* pSnow = new (std::nothrow) Snow( this, &m_RootNode, pGlobe, string("snowfall"), g_Cfg.SnowCfg() ); if( ! pSnow || ! pSnow->Initialized() ) { AppLog::Ref().LogMsg("SceneGraph failed to allocate heap for snow"); return false; } tr = translate( mat4(1.0), vec3(0, 380, 0) ); pSnow->GetNodeData().W() *= tr; m_map.insert( ActorIdPair( pSnow->Id(), pSnow) ); /* // Snowfall Snowfall* pSnowfall = new (std::nothrow) Snowfall( this, &m_RootNode, string("snowfall"), g_Cfg.SnowfallCfg() ); if( ! pSnowfall || ! pSnowfall->Initialized() ) { AppLog::Ref().LogMsg("SceneGraph failed to allocate heap for snowfall"); return false; } tr = translate( mat4(1.0), vec3(0, 350, 0) ); pSnowfall->GetNodeData().W() *= tr; m_map.insert( ActorIdPair( pSnowfall->Id(), pSnowfall) ); */ // lake Lake* pLake = new (std::nothrow) Lake( this, pTerrain, string("lake"), 180, 390, g_Cfg.AssetsDir() + string("water.jpg"), g_Cfg.AssetsDir() + string("water-alphamap.bmp"), string("") ); if( ! pLake || ! pLake->Initialized() ) { AppLog::Ref().LogMsg("SceneGraph failed to initialized the Lake"); return false; } tr = translate( mat4(1.0), vec3(0,344,168) ); mW = rotate( mW, -90.0f, vec3(0, 1, 0) ); pLake->GetNodeData().W() *= (tr * mW); m_map.insert( ActorIdPair( pLake->Id(), pLake) ); // house House* pHouse = new (std::nothrow) House( this, pTerrain, string("house"), g_Cfg.HouseCfg() ); if( ! pHouse || ! pHouse->Initialized() ) { AppLog::Ref().LogMsg("SceneGraph failed initialize the house"); return false; } tr = translate( mat4(1.0), vec3(20, 412, -125) ); pHouse->GetNodeData().W() *= tr; m_map.insert( ActorIdPair( pHouse->Id(), pHouse) ); // Tree Tree* pTree = new (std::nothrow) Tree( this, pTerrain, string("Tree"), g_Cfg.AssetsDir() + string("bark_1.jpg"), g_Cfg.AssetsDir() + string("bark_1_bump.jpg") ); if( ! pTree || ! pTree->Initialized() ) { AppLog::Ref().LogMsg("SceneGraph failed to allocate heap for Tree"); return false; } tr = translate( mat4(1.0), vec3(0, 313, 45) ); pTree->GetNodeData().W() *= tr; m_map.insert( ActorIdPair( pTree->Id(), pTree) ); return true; }
glm::mat4 Transform::getTransformationMatrix() const { mat4 translationMatrix = glm::translate(mat4(), translation); mat4 rotationMatrixX = glm::rotate(mat4(), rotation.x, vec3(1.0f, 0.0f, 0.0f)); mat4 rotationMatrixY = glm::rotate(mat4(), rotation.y, vec3(0.0f, 1.0f, 0.0f)); mat4 rotationMatrixZ = glm::rotate(mat4(), rotation.z, vec3(0.0f, 0.0f, 1.0f)); mat4 scaleMatrix = glm::scale(mat4(), scale); return translationMatrix * rotationMatrixX * rotationMatrixY * rotationMatrixZ * scaleMatrix; }
mat4 const& Model::getModelMatrix() const { if (!validModelMatrix) { mat4 scaleMatrix = glm::scale(mat4(), scale); mat4 rotateX = rotate(mat4(), rotation.x, vec3(1, 0, 0)); mat4 rotateY = rotate(mat4(), rotation.y, vec3(0, 1, 0)); mat4 rotateZ = rotate(mat4(), rotation.z, vec3(0, 0, 1)); mat4 translateMatrix = translate(mat4(), position); modelMatrix = translateMatrix * rotateZ * rotateY * rotateX * scaleMatrix; validModelMatrix = true; validInverseModelMatrix = false; } return modelMatrix; }