void drawWorld(int player) { int i; nebu_Video_CheckErrors("before world"); setupLights(eWorld); if (gSettingsCache.show_recognizer && game->player[player].data->speed != SPEED_GONE) { drawRecognizer(); } if (gSettingsCache.show_wall == 1) { glColor3f(1,1,1); drawWalls(); } setupLights(eCycles); drawPlayers(player); setupLights(eWorld); { TrailMesh mesh; mesh.pVertices = (vec3*) malloc(1000 * sizeof(vec3)); mesh.pNormals = (vec3*) malloc(1000 * sizeof(vec3)); mesh.pColors = (unsigned char*) malloc(1000 * 4 * sizeof(float)); mesh.pTexCoords = (vec2*) malloc(1000 * sizeof(vec2)); mesh.pIndices = (unsigned short*) malloc(1000 * 2); for(i = 0; i < game->players; i++) { if (game->player[i].data->trail_height > 0 ) { int vOffset = 0; int iOffset = 0; mesh.iUsed = 0; trailGeometry(game->player + i, gPlayerVisuals + i, &mesh, &vOffset, &iOffset); bowGeometry(game->player + i, gPlayerVisuals + i, &mesh, &vOffset, &iOffset); trailStatesNormal(game->player + i, gScreen->textures[TEX_DECAL]); trailRender(&mesh); trailStatesRestore(); } } free(mesh.pVertices); free(mesh.pNormals); free(mesh.pColors); free(mesh.pTexCoords); free(mesh.pIndices); } for(i = 0; i < game->players; i++) if (game->player[i].data->trail_height > 0 ) drawTrailLines(game->player + i, gPlayerVisuals + i); nebu_Video_CheckErrors("after world"); }
void View::initializeGL() { cout << "Using OpenGL Version " << glGetString(GL_VERSION) << endl << endl; glEnable(GL_TEXTURE_2D); createShaderPrograms(); // All OpenGL initialization *MUST* be done during or after this // method. Before this method is called, there is no active OpenGL // context and all OpenGL calls have no effect. // Start a timer that will try to get 60 frames per second (the actual // frame rate depends on the operating system and other running programs) //time.start(); //timer.start(1000 / 60); // Start the drawing timer m_timer.start(1000.0f / MAX_FPS); // Center the mouse, which is explained more in mouseMoveEvent() below. // This needs to be done here because the mouse may be initially outside // the fullscreen window and will not automatically receive mouse move // events. This occurs if there are two monitors and the mouse is on the // secondary monitor. QCursor::setPos(mapToGlobal(QPoint(width() / 2, height() / 2))); glClearColor(0.0f,0.0f,0.0f,0.0f); glEnable(GL_COLOR_MATERIAL); glShadeModel(GL_SMOOTH); // Enable depth testing, so that objects are occluded based on depth instead of drawing order glEnable(GL_DEPTH_TEST); // Setup blending glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); // Setup the cube map setupCubeMap(); // Enable alpha glEnable(GL_ALPHA_TEST); setupScene(); // Load the snow texture m_snowflakeTextures.push_back( ResourceLoader::loadTexture( ":/textures/textures/snowflake_design.png" ) ); m_snowflakeTextures.push_back( ResourceLoader::loadTexture( ":/textures/textures/second-snowflake.png" ) ); m_snowflakeTextures.push_back( ResourceLoader::loadTexture( ":/textures/textures/snowball-texture.png" ) ); m_snowflakeTextures.push_back( ResourceLoader::loadTexture( ":/textures/textures/snowflake-icon.png" ) ); m_snowflakeTextures.push_back( ResourceLoader::loadTexture( ":/textures/textures/actual-snowflake.png" ) ); m_snowEmitter.setTextures(&m_snowflakeTextures); m_snowTextureId = ResourceLoader::loadTexture( ":/textures/textures/plain-surface.jpg" ); updateCamera(); setupLights(); glFrontFace(GL_CCW); paintGL(); }
/** * Initializes the openGL settings */ void GLWindow::setupOpenGL(){ //setup the viewport and the perspective transformation matrix glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix gluPerspective(45.0, (double)w/h,0.1,150.0); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix // set the colour of the background, as well as other shading options glClearColor(1.0, 1.0, 1.0, 0); // glClearColor(0.0, 0.0, 0.0, 0); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations glEnable(GL_BLEND); //turn on antialiasing glEnable(GL_POINT_SMOOTH); glEnable(GL_LINE_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glBlendFunc(GL_SRC_ALPHA ,GL_ONE_MINUS_SRC_ALPHA); setupLights(); }
void Scene::init() { // Options this->viewMode = VIEW; this->selectMode = SELECT_NONE; // Background setBackgroundColor(backColor = QColor(50,50,60)); // Lights setupLights(); // Camera setupCamera(); // Material float mat_ambient[] = {0.1745f, 0.01175f, 0.01175f, 1.0f}; float mat_diffuse[] = {0.65f, 0.045f, 0.045f, 1.0f}; float mat_specular[] = {0.09f, 0.09f, 0.09f, 1.0f}; float high_shininess = 100; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialf(GL_FRONT, GL_SHININESS, high_shininess); // Redirect keyboard setShortcut( HELP, Qt::CTRL+Qt::Key_H); }
void setMatrices(const aiScene * scene) { // Set up the projection and model-view matrices GLfloat aspectRatio = (GLfloat)window.GetWidth()/window.GetHeight(); GLfloat nearClip = 0.1f; GLfloat farClip = 500.0f; GLfloat fieldOfView = 45.0f; // Degrees glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fieldOfView, aspectRatio, nearClip, farClip); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(current_location.x, current_location.y, current_location.z, current_location.x + current_forward.x, current_location.y + current_forward.y, current_location.z + current_forward.z, 0.0f, 1.0f, 0.0f); setupLights(); // Pass in our view matrix for cubemapping purposes // note: this may not be the best place to actually pass it to the shader... int shaderNum = 1; GLfloat* vMatrix = new GLfloat[16]; glGetFloatv(GL_MODELVIEW_MATRIX, vMatrix); // // Ugly, ugly, UGLY! // aiMatrix4x4 invertMe = aiMatrix4x4(vMatrix[0], vMatrix[1], vMatrix[2], vMatrix[3], vMatrix[4], vMatrix[5], vMatrix[6], vMatrix[7], vMatrix[8], vMatrix[9], vMatrix[10], vMatrix[11], vMatrix[12], vMatrix[13], vMatrix[14], vMatrix[15]); // aiMatrix4x4 inverted = invertMe.Inverse(); // GLfloat* vInvMatrix = new GLfloat{ inverted.a1, inverted.a2, inverted.a3, inverted.a4, inverted.b1, inverted.b2, inverted.b3, inverted.b4, inverted.c1, inverted.c2, inverted.c3, inverted.c4}; GLint vM = glGetUniformLocation(shaders[shaderNum]->programID(), "viewMatrix"); glUniformMatrix4fv(vM,1,true,vMatrix); applyMatrixTransform(scene->mRootNode); }
void Init() { setupLights(); ground.Init(); for (int i = 0; i < 20; i++) { obstacles[i].Init(); } }
void Display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); setupLights(); setupCamera(); drawBanana(30,cameraY+90,0); if (coins >= 5) { win = true; //sound for winning } if (cinematic) rotateCamera(); glColor3f(1,1,1); Draw_Skybox(cameraX, cameraY, cameraZ, 400, 800, 400); if (Levels.size() > 0) { if (Levels[0].y <cameraY - 100) { printf("deleting level"); Levels.erase(Levels.begin()); // for (int j = 0; j<Levels.size() - 1; j++) { // Levels[j] = Levels[j + 1]; // } // Levels.pop_back(); if (Levels.size()>0) { Levels[0].levelBefore = NULL; } } } char result[10]; sprintf(result, "%i", coins); //std::string name = "Score: ", result; displayText(50, cameraY + 110, 0, 1, 1, 1, result); if (!lost&!win) { createScene(); character.drawCharacter(); //std::string name = "Score: "; // char numstr[2]; /// result = name + numstr; } else { if (lost) displayText(-20, cameraY + 100, 0, 1, 1, 1, "GAME OVER!"); if (win) displayText(-20, cameraY + 100, 0, 1, 1, 1, "YOU WON :)"); } glFlush(); }
void environmentMatrixTransform(const aiScene * scene, int face) { STVector3 facingDir, upDir; switch (face) { case 0: facingDir = STVector3(-1,0,0); upDir = STVector3(0,1,0); break; case 1: facingDir = STVector3(1,0,0); upDir = STVector3(0,1,0); break; case 2: facingDir = STVector3(0,-1,0); upDir = STVector3(0,0,1); break; case 3: facingDir = STVector3(0,1,0); upDir = STVector3(0,0,-1); break; case 4: facingDir = STVector3(0,0,1); upDir = STVector3(0,1,0); break; case 5: facingDir = STVector3(0,0,-1); upDir = STVector3(0,1,0); break; default: printf("Your face is invalid!\n"); break; } GLfloat aspectRatio = 1.0f; GLfloat nearClip = 0.1f; GLfloat farClip = 500.0f; GLfloat fieldOfView = 90.0f; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fieldOfView, aspectRatio, nearClip, farClip); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(statue_location.x, statue_location.y, statue_location.z, statue_location.x + facingDir.x, statue_location.y + facingDir.y, statue_location.z + facingDir.z, upDir.x, upDir.y, upDir.z); setupLights(); applyMatrixTransform(scene->mRootNode); }
void View::paintGL() { updateCamera(); setupLights(); // Update the fps int time = m_clock.elapsed(); m_fps = 1000.f / (time - m_prevTime); m_prevTime = time; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glMatrixMode(GL_MODELVIEW); glPushMatrix(); // NOTE: Opaque objects must be rendered before transparent. This means // objects before snowflakes. glEnable(GL_LIGHTING); // Render all the objects in the scene renderScene(); if( m_showUnitAxis ) { glDisable(GL_LIGHTING); drawUnitAxis(0.f,0.f,0.f); //draw light GLfloat position[] = { 5.0f, 5.5f, 5.0f, 1.0f }; drawUnitAxis(position[0],position[1],position[2]); glEnable(GL_LIGHTING); } // Render dem snowflakes glEnable(GL_BLEND); glDisable(GL_LIGHTING); m_snowEmitter.drawSnowflakes(); glEnable(GL_LIGHTING); glDisable(GL_BLEND); glPopMatrix(); // Display the frame //glFlush(); //swapBuffers(); // Paint GUI paintUI(); }
hkDefaultPhysicsDemo::hkDefaultPhysicsDemo(hkDemoEnvironment* env, DemoFlags flags) : hkDefaultDemo(env), m_mouseSpring(HK_NULL), m_mouseSpringMaxRelativeForce(1000.0f), m_physicsViewersContext(HK_NULL), m_displayToiInformation(false), m_world(HK_NULL), m_flags(flags) { hkReferencedObject::lockAll(); m_physicsStepCounter = 0; //HK_ON_DETERMINISM_CHECKS_ENABLED(hkCheckDeterminismUtil::createInstance()); //HK_ON_DETERMINISM_CHECKS_ENABLED(hkCheckDeterminismUtil::getInstance().start()); // Disable warnings that commonly occur in the demos hkError::getInstance().setEnabled(0x6e8d163b, false); // hkpMoppUtility.cpp:18 hkError::getInstance().setEnabled(0x34df5494, false); //hkGeometryUtility.cpp:26 hkError::getInstance().setEnabled(0xf013323d, false); //hkBroadphaseBorder m_oldForceMultithreadedSimulation = hkpWorld::m_forceMultithreadedSimulation; hkpWorld::m_forceMultithreadedSimulation = env->m_options->m_forceMT; m_physicsViewersContext = new hkpPhysicsContext; if ( m_env->m_window ) { hkpPhysicsContext::registerAllPhysicsProcesses(); // all physics only ones } hkMemory::getInstance().m_memoryState = hkMemory::MEMORY_STATE_OK; hkMemory::getInstance().m_criticalMemoryLimit = 0x7fffffff; // Most physics demos look good with shadows m_forcedFPSChange = false; m_simulationStarted = false; if (m_env->m_window) { setupLights(m_env); // after we decide if we want shadows } hkReferencedObject::unlockAll(); #if defined(HK_PLATFORM_MULTI_THREAD) && (HK_CONFIG_THREAD == HK_CONFIG_MULTI_THREADED) hkpWorld::registerWithJobQueue( m_jobQueue ); #endif }
void CMeshViewer::setMesh(const shared_ptr<CMesh>& pMesh) { m_sceneObject.setMesh(pMesh); // evaluate the scale of the object m_scaleFactor = ceilf(log10f(m_sceneObject.getRadius())); // point the camera at the mesh m_camera.init(m_sceneObject); // Remove me: dev.info. CLogger::get() << "Camera at (" << m_camera.x << ", " << m_camera.y << ", " << m_camera.z << ").\n"; CLogger::get() << " looking at (" << m_camera.lookAt.x << ", " << m_camera.lookAt.y << ", " << m_camera.lookAt.z << ").\n"; CLogger::get() << " Z-clipping: near = " << m_camera.zNear << ", far =" << m_camera.zFar << ".\n"; adaptViewport(); setupLights(); }
void drawWalls(void) { int i; setupLights(eCyclesWorld); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); for(i = 0; i < gWorld->arena_shader.passes; i++) { video_Shader_Setup(& gWorld->arena_shader, i); video_Shader_Geometry(gWorld->arena, TRI_MESH, i); video_Shader_Cleanup(& gWorld->arena_shader, i); } glDisable(GL_BLEND); glDisable(GL_CULL_FACE); }
void GlutFramework::displayFramework() { if(displayTimer.isStopped()) { // Start the timer on the initial frame displayTimer.start(); } glClearColor(0.0, 0.0, 0.0, 1.0); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // Clear once displayTimer.stop(); // Stop the timer and get the elapsed time in seconds elapsedTimeInSeconds = displayTimer.getElapsedSeconds(); // seconds setupLights(); setDisplayMatricies(); display(elapsedTimeInSeconds); glutSwapBuffers(); displayTimer.start(); // reset the timer to calculate the time for the next frame }
void initOpenGL() { // Initialize GLEW on Windows, to make sure that OpenGL 2.0 is loaded #ifdef FRAMEWORK_USE_GLEW GLint error = glewInit(); if (GLEW_OK != error) { std::cerr << glewGetErrorString(error) << std::endl; exit(-1); } if (!GLEW_VERSION_2_0 || !GL_EXT_framebuffer_object) { std::cerr << "This program requires OpenGL 2.0 and FBOs" << std::endl; exit(-1); } #endif // This initializes OpenGL with some common defaults. More info here: // http://www.sfml-dev.org/tutorials/1.6/window-opengl.php glClearDepth(1.0f); glClearColor(0.3f, 0.25f, 0.7f, 1.0f); glEnable(GL_DEPTH_TEST); setupLights(); }
//Initialisation function. void init(int argc, char **argv) { //Initialise GLUT. glutInit(&argc, argv); // Use doule buffering. glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(760, 760); //Create window. glutCreateWindow("Come Fly With Me - by Chris Patuzzo"); //Set up camera. glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90, 1, 0.00001, 1 / SCALE_FACTOR); glMatrixMode(GL_MODELVIEW); //Set the clear color. glClearColor(0, 0, 0, 1); //Use z-buffer, lighting, normal scaling. glEnable(GL_DEPTH_TEST); //Set up two lights; the sun and its reflection. setupLights(); //Use vertex arrays. glEnableClientState(GL_VERTEX_ARRAY); glEnable(GL_TEXTURE_2D); //Load skybox and objects. loadSkybox(); loadObjects(); //Calculate cloud plane. calculateCloudPlane(); }
hkDefaultAnimationDemo::hkDefaultAnimationDemo(hkDemoEnvironment* env) : hkDefaultDemo (env) //m_animationViewersContext(HK_NULL) { // eg: // m_animationViewersContext= new hkAnimationContext; // hkAnimationContext::registerAllAnimationProcesses(); // all physics only ones // Most of the default animations hover above the ground, so we don't want shadows // until they are reauthored forceShadowState(false); setupLights(m_env); // after we decide if we want shadows // Disable compression & mapping reports if(m_env->m_reportingLevel < hkDemoEnvironment::REPORT_INFO ) { hkError::getInstance().setEnabled(0x432434a4, false); // Track analysis report hkError::getInstance().setEnabled(0x432434a5, false); // Delta/wavelet constructor report hkError::getInstance().setEnabled(0x54e4323e, false); // hkaSkeletonMapperUtils::createMapping report hkError::getInstance().setEnabled(0xf0d1e423, false); // 'Could not realize an inplace texture of type PNG.' hkError::getInstance().setEnabled(0x36118e94, false); // Spline constructor report } }
SpiralScene::SpiralScene() { setupCamera(); setupObjects(); setupLights(); }
CharacterDemo::CharacterDemo(hkDemoEnvironment* env) : hkDefaultPhysicsDemo(env) { // // Setup the camera // { hkVector4 from( 0.0f, 20.0f, -80.0f); hkVector4 to ( 0.0f, 0.0f, 0.0f); hkVector4 up ( 0.0f, 1.0f, 0.0f); setupDefaultCameras( env, from, to, up ); // disable back face culling setGraphicsState(HKG_ENABLED_CULLFACE, false); // don't really want shadows as makes it too dark forceShadowState(false); setupLights(m_env); // so that the extra lights are added // float lightDir[] = { 0, -0.5f, -1 }; // setSoleDirectionLight(m_env, lightDir, 0xffffffff ); } // // Create the world // { hkpWorldCinfo info; info.setBroadPhaseWorldSize( 350.0f ); info.m_gravity.set(0,0,-9.8f); info.m_collisionTolerance = 0.1f; m_world = new hkpWorld( info ); m_world->lock(); hkpAgentRegisterUtil::registerAllAgents(m_world->getCollisionDispatcher()); setupGraphics(); } // Load the level { hkVector4 tkScaleFactor(.32f,.32f,.32f); hkString fullname("Resources/Physics/Tk/CharacterController/"); // We load our test case level. //fullname += "testcases.tk"; fullname += "level.tk"; hkpShape* moppShape = GameUtils::loadTK2MOPP(fullname.cString(),tkScaleFactor, -1.0f); HK_ASSERT2(0x64232cc0, moppShape,"TK file failed to load to MOPP in GameUtils::loadTK2MOPP."); hkpRigidBodyCinfo ci; ci.m_shape = moppShape; ci.m_motionType = hkpMotion::MOTION_FIXED; ci.m_collisionFilterInfo = hkpGroupFilter::calcFilterInfo( 0, 1 ); hkpRigidBody* entity = new hkpRigidBody(ci); moppShape->removeReference(); m_world->addEntity(entity); entity->removeReference(); } // Add a ladder hkVector4 baseSize( 1.0f, 0.5f, 3.6f); { hkpRigidBodyCinfo rci; rci.m_shape = new hkpBoxShape( baseSize ); rci.m_position.set(3.4f, 8.f, 2); rci.m_motionType = hkpMotion::MOTION_FIXED; hkpRigidBody* ladder = new hkpRigidBody(rci); rci.m_shape->removeReference(); m_world->addEntity(ladder)->removeReference(); // Add a property so we can identify this as a ladder hkpPropertyValue val(1); ladder->addProperty(HK_OBJECT_IS_LADDER, val); // Color the ladder so we can see it clearly HK_SET_OBJECT_COLOR((hkUlong)ladder->getCollidable(), 0x7f1f3f1f); } // // Create a character proxy object // { // Construct a shape hkVector4 vertexA(0,0, 0.4f); hkVector4 vertexB(0,0,-0.4f); // Create a capsule to represent the character standing m_standShape = new hkpCapsuleShape(vertexA, vertexB, .6f); // Create a capsule to represent the character crouching // Note that we create the smaller capsule with the base at the same position as the larger capsule. // This means we can simply swap the shapes without having to reposition the character proxy, // and if the character is standing on the ground, it will still be on the ground. vertexA.setZero4(); m_crouchShape = new hkpCapsuleShape(vertexA, vertexB, .6f); // Construct a Shape Phantom m_phantom = new hkpSimpleShapePhantom( m_standShape, hkTransform::getIdentity(), hkpGroupFilter::calcFilterInfo(0,2) ); // Add the phantom to the world m_world->addPhantom(m_phantom); m_phantom->removeReference(); // Construct a character proxy hkpCharacterProxyCinfo cpci; cpci.m_position.set(-9.1f, 35, .4f); cpci.m_staticFriction = 0.0f; cpci.m_dynamicFriction = 1.0f; cpci.m_up.setNeg4( m_world->getGravity() ); cpci.m_up.normalize3(); cpci.m_userPlanes = 4; cpci.m_maxSlope = HK_REAL_PI / 3.f; cpci.m_shapePhantom = m_phantom; m_characterProxy = new hkpCharacterProxy( cpci ); } // // Add in a custom friction model // { hkVector4 up( 0.f, 0.f, 1.f ); m_listener = new MyCharacterListener(); m_characterProxy->addCharacterProxyListener(m_listener); } // // Create the Character state machine and context // { hkpCharacterState* state; hkpCharacterStateManager* manager = new hkpCharacterStateManager(); state = new hkpCharacterStateOnGround(); manager->registerState( state, HK_CHARACTER_ON_GROUND); state->removeReference(); state = new hkpCharacterStateInAir(); manager->registerState( state, HK_CHARACTER_IN_AIR); state->removeReference(); state = new hkpCharacterStateJumping(); manager->registerState( state, HK_CHARACTER_JUMPING); state->removeReference(); state = new hkpCharacterStateClimbing(); manager->registerState( state, HK_CHARACTER_CLIMBING); state->removeReference(); m_characterContext = new hkpCharacterContext(manager, HK_CHARACTER_ON_GROUND); manager->removeReference(); } // Current camera angle about up m_currentAngle = HK_REAL_PI * 0.5f; m_world->unlock(); }
CubeScene::CubeScene() { setupCamera(); setupObjects(); setupLights(); }
int main(int argc, char** argv) { if (!glfwInit()) // 初始化glfw库 { std::cout << "Error::GLFW could not initialize GLFW!" << std::endl; return -1; } // 开启OpenGL 3.3 core profile std::cout << "Start OpenGL core profile version 3.3" << std::endl; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // 创建窗口 GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo of multiple lighting source", NULL, NULL); if (!window) { std::cout << "Error::GLFW could not create winddow!" << std::endl; glfwTerminate(); return -1; } // 创建的窗口的context指定为当前context glfwMakeContextCurrent(window); // 注册窗口键盘事件回调函数 glfwSetKeyCallback(window, key_callback); // 注册鼠标事件回调函数 glfwSetCursorPosCallback(window, mouse_move_callback); // 注册鼠标滚轮事件回调函数 glfwSetScrollCallback(window, mouse_scroll_callback); // 鼠标捕获 停留在程序内 glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // 初始化GLEW 获取OpenGL函数 glewExperimental = GL_TRUE; // 让glew获取所有拓展函数 GLenum status = glewInit(); if (status != GLEW_OK) { std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION) << " error string:" << glewGetErrorString(status) << std::endl; glfwTerminate(); return -1; } // 设置视口参数 glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // Section1 准备顶点数据 // 指定顶点属性数据 顶点位置 纹理 法向量 GLfloat vertices[] = { -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f,1.0f, // A 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // B 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // C 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // C -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // D -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, // A -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, // E -0.5f, 0.5f, -0.5f, 0.0, 1.0f, 0.0f, 0.0f, -1.0f, // H 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f, // G 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f, // G 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, // F -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, // E -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, // D -0.5f, 0.5f, -0.5f, 1.0, 1.0f, -1.0f, 0.0f, 0.0f, // H -0.5f, -0.5f, -0.5f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, // E -0.5f, -0.5f, -0.5f,1.0f, 0.0f, -1.0f, 0.0f, 0.0f, // E -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // A -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, // D 0.5f, -0.5f, -0.5f,1.0f, 0.0f, 1.0f, 0.0f, 0.0f, // F 0.5f, 0.5f, -0.5f,1.0f, 1.0f, 1.0f, 0.0f, 0.0f, // G 0.5f, 0.5f, 0.5f,0.0f, 1.0f, 1.0f, 0.0f, 0.0f, // C 0.5f, 0.5f, 0.5f,0.0f, 1.0f, 1.0f, 0.0f, 0.0f, // C 0.5f, -0.5f, 0.5f,0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // B 0.5f, -0.5f, -0.5f,1.0f, 0.0f, 1.0f, 0.0f, 0.0f, // F 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // G -0.5f, 0.5f, -0.5f, 0.0, 1.0f, 0.0f, 1.0f, 0.0f, // H -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, // D -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, // D 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // C 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // G -0.5f, -0.5f, 0.5f,0.0f, 0.0f, 0.0f, -1.0f, 0.0f, // A -0.5f, -0.5f, -0.5f,0.0f, 1.0f, 0.0f, -1.0f, 0.0f, // E 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, -1.0f, 0.0f, // F 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, -1.0f, 0.0f, // F 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, // B -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, // A }; glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; glm::vec3 pointLightPositions[] = { glm::vec3(0.7f, 0.2f, 2.0f), glm::vec3(2.3f, -3.3f, -4.0f), glm::vec3(-4.0f, 2.0f, -12.0f), glm::vec3(0.0f, 0.0f, -3.0f) }; // 创建物体缓存对象 GLuint VAOId, VBOId; // Step1: 创建并绑定VAO对象 glGenVertexArrays(1, &VAOId); glBindVertexArray(VAOId); // Step2: 创建并绑定VBO 对象 传送数据 glGenBuffers(1, &VBOId); glBindBuffer(GL_ARRAY_BUFFER, VBOId); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Step3: 指定解析方式 并启用顶点属性 // 顶点位置属性 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)0); glEnableVertexAttribArray(0); // 顶点纹理坐标 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)(3 * sizeof(GL_FLOAT))); glEnableVertexAttribArray(1); // 顶点法向量属性 glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)(5 * sizeof(GL_FLOAT))); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // 创建光源的VAO GLuint lampVAOId; glGenVertexArrays(1, &lampVAOId); glBindVertexArray(lampVAOId); glBindBuffer(GL_ARRAY_BUFFER, VBOId); // 重用上面的数据 无需重复发送顶点数据 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)0); glEnableVertexAttribArray(0); // 只需要顶点位置即可 glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // Section2 准备着色器程序 Shader shader("cube.vertex", "cube.frag"); Shader lampShaer("lamp.vertex", "lamp.frag"); // Section3 准备diffuseMap和specularMap GLint diffuseMap = TextureHelper::load2DTexture("../../resources/textures/container_diffuse.png"); GLint specularMap = TextureHelper::load2DTexture("../../resources/textures/container_specular.png"); // 设置diffuse map的纹理单元 shader.use(); glUniform1i(glGetUniformLocation(shader.programId, "material.diffuseMap"), 0); // 设置specular map的纹理单元 shader.use(); glUniform1i(glGetUniformLocation(shader.programId, "material.specularMap"), 1); glEnable(GL_DEPTH_TEST); // 开始游戏主循环 while (!glfwWindowShouldClose(window)) { GLfloat currentFrame = (GLfloat)glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); // 处理例如鼠标 键盘等事件 do_movement(); // 根据用户操作情况 更新相机属性 // 清除颜色缓冲区 重置为指定颜色 //glClearColor(0.18f, 0.04f, 0.14f, 1.0f); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 projection = glm::perspective(camera.mouse_zoom, (GLfloat)(WINDOW_WIDTH) / WINDOW_HEIGHT, 1.0f, 100.0f); // 投影矩阵 glm::mat4 view = camera.getViewMatrix(); // 视变换矩阵 // 这里填写场景绘制代码 glBindVertexArray(VAOId); shader.use(); setupLights(shader, pointLightPositions, sizeof(pointLightPositions) / sizeof(pointLightPositions[0])); // 设置材料光照属性 // 启用diffuseMap glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMap); // 启用specularMap glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, specularMap); GLint objectShininessLoc = glGetUniformLocation(shader.programId, "material.shininess"); glUniform1f(objectShininessLoc, 32.0f); // 设置观察者位置 GLint viewPosLoc = glGetUniformLocation(shader.programId, "viewPos"); glUniform3f(viewPosLoc, camera.position.x, camera.position.y, camera.position.z); // 设置变换矩阵 glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"), 1, GL_FALSE, glm::value_ptr(view)); // 绘制多个立方体 glm::mat4 model; for (int i = 0; i < sizeof(cubePositions) / sizeof(cubePositions[0]); ++i) { model = glm::mat4(); model = glm::translate(model, cubePositions[i]); GLfloat angle = 20.0f * i; model = glm::rotate(model, angle, glm::vec3(1.0f, 0.3f, 0.5f)); glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); } // 利用立方体模拟点光源 glBindVertexArray(lampVAOId); lampShaer.use(); glUniformMatrix4fv(glGetUniformLocation(lampShaer.programId, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(lampShaer.programId, "view"), 1, GL_FALSE, glm::value_ptr(view)); for (int i = 0; i < sizeof(pointLightPositions) / sizeof(pointLightPositions[0]); ++i) { model = glm::mat4(); model = glm::translate(model, pointLightPositions[i]); model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f)); glUniformMatrix4fv(glGetUniformLocation(lampShaer.programId, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); glUseProgram(0); glfwSwapBuffers(window); // 交换缓存 } // 释放资源 glDeleteVertexArrays(1, &VAOId); glDeleteBuffers(1, &VBOId); glDeleteVertexArrays(1, &lampVAOId); glfwTerminate(); return 0; }
/** * This method is used to draw the scene. */ void GLWindow::draw(){ //clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); //we will now place the camera setupGLCamera(); //and set up the lights (do this so that the position is specified in world coordinates, not in camera ones). setupLights(); /** If we want fog... */ /* GLfloat fogColor[4]= {0.5f, 0.5f, 0.5f, 1.0f}; // Fog Color glFogi(GL_FOG_MODE, GL_LINEAR); // Fog Mode glFogfv(GL_FOG_COLOR, fogColor); // Set Fog Color glFogf(GL_FOG_DENSITY, 0.35f); // How Dense Will The Fog Be glHint(GL_FOG_HINT, GL_DONT_CARE); // Fog Hint Value glFogf(GL_FOG_START, 20.0f); // Fog Start Depth glFogf(GL_FOG_END, 80.0f); // Fog End Depth glEnable(GL_FOG); // Enables GL_FOG */ if (Globals::drawCubeMap) drawCubeMap(); glColor3d(1, 1, 1); //and then draw the application stuff if (Globals::app) Globals::app->draw(); if (Globals::drawGroundPlane && Globals::app) Globals::app->drawGround(); //no more texture mapping or lighting needed glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); if (Globals::drawShadows && Globals::drawGroundPlane && Globals::app) drawShadows(); glColor3d(1,1,1); if (Globals::app) Globals::app->drawExtras(); if (Globals::drawGlobalAxes) drawAxes(); //wait until the required ammount of time has passed (respect the desired FPS requirement) while (fpsTimer.timeEllapsed()<1.0/Globals::desiredFrameRate); if (Globals::drawFPS) drawFPSandPerf(fpsTimer.timeEllapsed(), timeSpentProcessing/(1/Globals::desiredFrameRate)); //print a screenshot if needed if (Globals::drawScreenShots){ static int screenShotNumber = 0; char fName[100]; sprintf(fName, "..\\screenShots\\ss%05d.bmp", screenShotNumber); screenShotNumber++; GLUtils::saveScreenShot(fName, 0, 0, w, h); } if (Globals::drawWorldShots && Globals::app ){ static int worldShotNumber = 0; char fName[100]; sprintf(fName, "..\\worldShots\\ws%05d.obj", worldShotNumber); worldShotNumber++; FILE* fp = fopen( fName, "w" ); fprintf( fp, "####\n" "#\n" "# OBJ File Generated by UBC-IMAGER character animation tool\n" "# Frame %05d\n" "#\n" "####\n\n", worldShotNumber ); Globals::app->renderToObjFile( fp, 0 ); fclose( fp ); } fpsTimer.restart(); }
void CColosseumCtrl::render() { if (m_initialized) { // Clear the backbuffer and the zbuffer if( FAILED( m_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 ) ) ) { g_directXStatus = -1; return; } // Begin the scene if (SUCCEEDED(m_pd3dDevice->BeginScene())) { // Setup the lights and materials if (setupLights()) { g_directXStatus = -1; return; } // Setup the world, view, and projection matrices if (setupMatrices()) { g_directXStatus = -1; return; } if (m_pd3dDevice->SetStreamSource(0, m_pVB, 0, sizeof(CUSTOMVERTEX))) { g_directXStatus = -1; return; } m_pd3dDevice->SetVertexShader(NULL); m_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX); D3DMATERIAL9 mtrl; mtrl.Diffuse.r = mtrl.Ambient.r = mtrl.Specular.r = 0.4f; mtrl.Diffuse.g = mtrl.Ambient.g = mtrl.Specular.g = 0.1f; mtrl.Diffuse.b = mtrl.Ambient.b = mtrl.Specular.b = 0.7f; mtrl.Diffuse.a = mtrl.Ambient.a = mtrl.Specular.a = 1.0f; mtrl.Emissive.r = 0.1f; mtrl.Emissive.g = 0.4f; mtrl.Emissive.b = 0.02f; mtrl.Emissive.a = 0.5f; m_pd3dDevice->SetMaterial(&mtrl); STRUCT_INSTANCES * instance = m_engineInteract->getFirstInstance(); while (instance) { if ( (instance->parent) && (instance->select == ITEM_CHECKED) ){ m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, instance->startIndex, instance->primitiveCount); } instance = instance->next; } // End the scene if( FAILED( m_pd3dDevice->EndScene() ) ) { g_directXStatus = -1; return; } } // Present the backbuffer contents to the display if( FAILED( m_pd3dDevice->Present( NULL, NULL, NULL, NULL ) ) ) { g_directXStatus = -1; return; } } }
void Scene::init() { loadTexture( "textures/BLANK.tiff", m_blankTex ); //addGameObject("models/TrollLowRes.obj", "textures/TrollColour.tiff", ngl::Vector(5,1.85,5), ngl::Vector(0,0,0), ngl::Vector(5,5,5)); //addGameObject("models/ControlBox1.obj", "textures/ControlBox1.tiff", ngl::Vector(3.5,-1,-4), ngl::Vector(0,-90,0), ngl::Vector(0.1,0.1,0.1)); // addGameObject("models/ControlBox2.obj", // "textures/ControlBox2.tiff", // ngl::Vector(6.0f,-1.0f,-4.0f,1.0f), // ngl::Vector(0.0f,-90.0f,0.0f,1.0f), // ngl::Vector(0.1f,0.1f,0.1f,1.0f)); // addGameObject("models/TNT.obj", // "textures/TNT.tiff", // ngl::Vector(6.0f,0.25f,-4.0f,1.0f), // ngl::Vector(0.0f,-90.0f,0.0f,1.0f), // ngl::Vector(0.1f,0.1f,0.1f,1.0f)); // addGameObject("models/Street.obj", // "textures/Street.tiff", // ngl::Vector(0.0f,-1.0f,0.0f,1.0f), // ngl::Vector(0.0f,0.0f,0.0f,1.0f), // ngl::Vector(20.0f,20.0f,20.0f,1.0f)); // addGameObject("models/Ruins.obj", // "textures/Ruins.tiff", // ngl::Vector(-1.0f,-1.0f,5.0f,1.0f), // ngl::Vector(0.0f,0.0f,0.0f,1.0f), // ngl::Vector(0.5f,0.5f,0.5f,1.0f)); // addGameObject("models/Ruins2.obj", // "textures/Ruins.tiff", // ngl::Vector(1.0f,-1.0f,1.0f,1.0f), // ngl::Vector(0.0f,0.0f,0.0f,1.0f), // ngl::Vector(0.5f,0.5f,0.5f,1.0f)); // addGameObject("models/Minebeams.obj", // "textures/Minebeams.tiff", // ngl::Vector(5.2f,-2.0f,0.6f,1.0f), // ngl::Vector(0.0f,0.0f,0.0f,1.0f), // ngl::Vector(0.42f,0.4f,0.65f,1.0f)); // addGameObject("models/Plane.obj", // "textures/Sky.jpg", // ngl::Vector(5.2f,2.0f,-8.0f,1.0f), // ngl::Vector(0.0f,0.0f,0.0f,1.0f), // ngl::Vector(10.0f,10.0f,10.0f,1.0f)); // addGameObject("models/Killerroo.obj", // "textures/Sky.jpg", // ngl::Vector(5.2f,2.0f,-8.0f,1.0f), // ngl::Vector(0.0f,0.0f,0.0f,1.0f), // ngl::Vector(10.0f,10.0f,10.0f,1.0f)); // addGameObject("models/WaterTower.obj", // "textures/WaterTower.tiff", // ngl::Vector(9.2f,-2.0f,1.6f,1.0f), // ngl::Vector(0.0f,0.0f,0.0f,1.0f), // ngl::Vector(0.1f,0.1f,0.1f,1.0f)); // for(unsigned int i = 0; i < m_gameObjects.size(); i++) // { // m_gameObjects[i].geo.createVBO(GL_STATIC_DRAW); // } ///////////////////////// setupLights(); std::cout << "Scene Created" << std::endl; }
int main() { if(glfwInit() == GL_FALSE) { std::cerr << "Failed to initialize GLFW" << std::endl; return -1; } defer(glfwTerminate()); glfwDefaultWindowHints(); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_SAMPLES, 4); GLFWwindow* window = glfwCreateWindow(800, 600, "Lighting", nullptr, nullptr); if(window == nullptr) { std::cerr << "Failed to open GLFW window" << std::endl; return -1; } defer(glfwDestroyWindow(window)); glfwMakeContextCurrent(window); if(glxwInit()) { std::cerr << "Failed to init GLXW" << std::endl; return -1; } glfwSwapInterval(1); glfwSetWindowSizeCallback(window, windowSizeCallback); glfwShowWindow(window); bool errorFlag = false; std::vector<GLuint> shaders; GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag); if(errorFlag) { std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl; return -1; } shaders.push_back(vertexShaderId); GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag); if(errorFlag) { std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl; return -1; } shaders.push_back(fragmentShaderId); GLuint programId = prepareProgram(shaders, &errorFlag); if(errorFlag) { std::cerr << "Failed to prepare program" << std::endl; return -1; } defer(glDeleteProgram(programId)); glDeleteShader(vertexShaderId); glDeleteShader(fragmentShaderId); // === prepare textures === GLuint textureArray[6]; int texturesNum = sizeof(textureArray)/sizeof(textureArray[0]); glGenTextures(texturesNum, textureArray); defer(glDeleteTextures(texturesNum, textureArray)); GLuint grassTexture = textureArray[0]; GLuint skyboxTexture = textureArray[1]; GLuint towerTexture = textureArray[2]; GLuint garkGreenTexture = textureArray[3]; GLuint redTexture = textureArray[4]; GLuint blueTexture = textureArray[5]; if(!loadDDSTexture("textures/grass.dds", grassTexture)) return -1; if(!loadDDSTexture("textures/skybox.dds", skyboxTexture)) return -1; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if(!loadDDSTexture("textures/tower.dds", towerTexture)) return -1; loadOneColorTexture(0.05f, 0.5f, 0.1f, garkGreenTexture); loadOneColorTexture(1.0f, 0.0f, 0.0f, redTexture); loadOneColorTexture(0.0f, 0.0f, 1.0f, blueTexture); // === prepare VAOs === GLuint vaoArray[5]; int vaosNum = sizeof(vaoArray)/sizeof(vaoArray[0]); glGenVertexArrays(vaosNum, vaoArray); defer(glDeleteVertexArrays(vaosNum, vaoArray)); GLuint grassVAO = vaoArray[0]; GLuint skyboxVAO = vaoArray[1]; GLuint towerVAO = vaoArray[2]; GLuint torusVAO = vaoArray[3]; GLuint sphereVAO = vaoArray[4]; // === prepare VBOs === GLuint vboArray[10]; int vbosNum = sizeof(vboArray)/sizeof(vboArray[0]); glGenBuffers(vbosNum, vboArray); defer(glDeleteBuffers(vbosNum, vboArray)); GLuint grassVBO = vboArray[0]; GLuint grassIndicesVBO = vboArray[1]; GLuint skyboxVBO = vboArray[2]; GLuint skyboxIndicesVBO = vboArray[3]; GLuint towerVBO = vboArray[4]; GLuint towerIndicesVBO = vboArray[5]; GLuint torusVBO = vboArray[6]; GLuint torusIndicesVBO = vboArray[7]; GLuint sphereVBO = vboArray[8]; GLuint sphereIndicesVBO = vboArray[9]; // === load models === GLsizei grassIndicesNumber, skyboxIndicesNumber, towerIndicesNumber, torusIndicesNumber, sphereIndicesNumber; GLenum grassIndexType, skyboxIndexType, towerIndexType, torusIndexType, sphereIndexType; if(!modelLoad("models/grass.emd", grassVAO, grassVBO, grassIndicesVBO, &grassIndicesNumber, &grassIndexType)) return -1; if(!modelLoad("models/skybox.emd", skyboxVAO, skyboxVBO, skyboxIndicesVBO, &skyboxIndicesNumber, &skyboxIndexType)) return -1; if(!modelLoad("models/tower.emd", towerVAO, towerVBO, towerIndicesVBO, &towerIndicesNumber, &towerIndexType)) return -1; if(!modelLoad("models/torus.emd", torusVAO, torusVBO, torusIndicesVBO, &torusIndicesNumber, &torusIndexType)) return -1; if(!modelLoad("models/sphere.emd", sphereVAO, sphereVBO, sphereIndicesVBO, &sphereIndicesNumber, &sphereIndexType)) return -1; glm::mat4 projection = glm::perspective(70.0f, 4.0f / 3.0f, 0.3f, 250.0f); GLint uniformMVP = getUniformLocation(programId, "MVP"); GLint uniformM = getUniformLocation(programId, "M"); GLint uniformTextureSample = getUniformLocation(programId, "textureSampler"); GLint uniformCameraPos = getUniformLocation(programId, "cameraPos"); GLint uniformMaterialSpecularFactor = getUniformLocation(programId, "materialSpecularFactor"); GLint uniformMaterialSpecularIntensity = getUniformLocation(programId, "materialSpecularIntensity"); GLint uniformMaterialEmission = getUniformLocation(programId, "materialEmission"); auto startTime = std::chrono::high_resolution_clock::now(); auto prevTime = startTime; Camera camera(window, glm::vec3(0, 0, 5), 3.14f /* toward -Z */, 0.0f /* look at the horizon */); glEnable(GL_DOUBLEBUFFER); glEnable(GL_CULL_FACE); glEnable(GL_MULTISAMPLE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glClearColor(0, 0, 0, 1); glUseProgram(programId); glUniform1i(uniformTextureSample, 0); bool directionalLightEnabled = true; bool pointLightEnabled = true; bool spotLightEnabled = true; bool wireframesModeEnabled = false; float lastKeyPressCheck = 0.0; const float keyPressCheckIntervalMs = 250.0f; setupLights(programId, directionalLightEnabled, pointLightEnabled, spotLightEnabled); while(glfwWindowShouldClose(window) == GL_FALSE) { if(glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) break; auto currentTime = std::chrono::high_resolution_clock::now(); float startDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - startTime).count(); float prevDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - prevTime).count(); prevTime = currentTime; float rotationTimeMs = 100000.0f; float currentRotation = startDeltaTimeMs / rotationTimeMs; float islandAngle = 360.0f*(currentRotation - (long)currentRotation); if(startDeltaTimeMs - lastKeyPressCheck > keyPressCheckIntervalMs) { if(glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS) { lastKeyPressCheck = startDeltaTimeMs; wireframesModeEnabled = !wireframesModeEnabled; if(wireframesModeEnabled) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } if(glfwGetKey(window, GLFW_KEY_M) == GLFW_PRESS) { lastKeyPressCheck = startDeltaTimeMs; bool enabled = camera.getMouseInterception(); camera.setMouseInterception(!enabled); } if(glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS) { lastKeyPressCheck = startDeltaTimeMs; directionalLightEnabled = !directionalLightEnabled; setupLights(programId, directionalLightEnabled, pointLightEnabled, spotLightEnabled); } if(glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS) { lastKeyPressCheck = startDeltaTimeMs; pointLightEnabled = !pointLightEnabled; setupLights(programId, directionalLightEnabled, pointLightEnabled, spotLightEnabled); } if(glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS) { lastKeyPressCheck = startDeltaTimeMs; spotLightEnabled = !spotLightEnabled; setupLights(programId, directionalLightEnabled, pointLightEnabled, spotLightEnabled); } } glm::vec3 cameraPos; camera.getPosition(&cameraPos); glUniform3f(uniformCameraPos, cameraPos.x, cameraPos.y, cameraPos.z); glm::mat4 view; camera.getViewMatrix(prevDeltaTimeMs, &view); glm::mat4 vp = projection * view; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // TODO implement ModelLoader and Model classes // tower glm::mat4 towerM = glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(-1.5f, -1.0f, -1.5f); glm::mat4 towerMVP = vp * towerM; glBindTexture(GL_TEXTURE_2D, towerTexture); glBindVertexArray(towerVAO); glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &towerMVP[0][0]); glUniformMatrix4fv(uniformM, 1, GL_FALSE, &towerM[0][0]); glUniform1f(uniformMaterialSpecularFactor, 1.0f); glUniform1f(uniformMaterialSpecularIntensity, 0.0f); glUniform3f(uniformMaterialEmission, 0.0f, 0.0f, 0.0f); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, towerIndicesVBO); glDrawElements(GL_TRIANGLES, towerIndicesNumber, towerIndexType, nullptr); // torus glm::mat4 torusM = glm::translate(0.0f, 1.0f, 0.0f) * glm::rotate((60.0f - 3.0f*islandAngle), 0.0f, 0.5f, 0.0f); glm::mat4 torusMVP = vp * torusM; glBindTexture(GL_TEXTURE_2D, garkGreenTexture); glBindVertexArray(torusVAO); glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &torusMVP[0][0]); glUniformMatrix4fv(uniformM, 1, GL_FALSE, &torusM[0][0]); glUniform1f(uniformMaterialSpecularFactor, 1.0f); glUniform1f(uniformMaterialSpecularIntensity, 1.0f); glUniform3f(uniformMaterialEmission, 0.0f, 0.0f, 0.0f); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, torusIndicesVBO); glDrawElements(GL_TRIANGLES, torusIndicesNumber, torusIndexType, nullptr); // grass glm::mat4 grassM = glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(0.0f, -1.0f, 0.0f); glm::mat4 grassMVP = vp * grassM; glBindTexture(GL_TEXTURE_2D, grassTexture); glBindVertexArray(grassVAO); glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &grassMVP[0][0]); glUniformMatrix4fv(uniformM, 1, GL_FALSE, &grassM[0][0]); glUniform1f(uniformMaterialSpecularFactor, 32.0f); glUniform1f(uniformMaterialSpecularIntensity, 2.0f); glUniform3f(uniformMaterialEmission, 0.0f, 0.0f, 0.0f); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, grassIndicesVBO); glDrawElements(GL_TRIANGLES, grassIndicesNumber, grassIndexType, nullptr); // skybox glm::mat4 skyboxM = glm::translate(cameraPos) * glm::scale(100.0f,100.0f,100.0f); glm::mat4 skyboxMVP = vp * skyboxM; glBindTexture(GL_TEXTURE_2D, skyboxTexture); glBindVertexArray(skyboxVAO); glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &skyboxMVP[0][0]); glUniformMatrix4fv(uniformM, 1, GL_FALSE, &skyboxM[0][0]); glUniform1f(uniformMaterialSpecularFactor, 1.0f); glUniform1f(uniformMaterialSpecularIntensity, 0.0f); glUniform3f(uniformMaterialEmission, 0.0f, 0.0f, 0.0f); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyboxIndicesVBO); glDrawElements(GL_TRIANGLES, skyboxIndicesNumber, skyboxIndexType, nullptr); // point light source if(pointLightEnabled) { glm::mat4 pointLightM = glm::translate(pointLightPos); glm::mat4 pointLightMVP = vp * pointLightM; glBindTexture(GL_TEXTURE_2D, redTexture); glBindVertexArray(sphereVAO); glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &pointLightMVP[0][0]); glUniformMatrix4fv(uniformM, 1, GL_FALSE, &pointLightM[0][0]); glUniform1f(uniformMaterialSpecularFactor, 1.0f); glUniform1f(uniformMaterialSpecularIntensity, 1.0f); glUniform3f(uniformMaterialEmission, 0.5f, 0.5f, 0.5f); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereIndicesVBO); glDrawElements(GL_TRIANGLES, sphereIndicesNumber, sphereIndexType, nullptr); } // spot light source if(spotLightEnabled) { glm::mat4 spotLightM = glm::translate(spotLightPos); glm::mat4 spotLightMVP = vp * spotLightM; glBindTexture(GL_TEXTURE_2D, blueTexture); glBindVertexArray(sphereVAO); glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &spotLightMVP[0][0]); glUniformMatrix4fv(uniformM, 1, GL_FALSE, &spotLightM[0][0]); glUniform1f(uniformMaterialSpecularFactor, 1.0f); glUniform1f(uniformMaterialSpecularIntensity, 1.0f); glUniform3f(uniformMaterialEmission, 0.5f, 0.5f, 0.5f); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereIndicesVBO); glDrawElements(GL_TRIANGLES, sphereIndicesNumber, sphereIndexType, nullptr); } glfwSwapBuffers(window); glfwPollEvents(); } return 0; }
PlatformsCharacterRbDemo::PlatformsCharacterRbDemo(hkDemoEnvironment* env) : hkDefaultPhysicsDemo(env) { // Setup the graphics { // Disable back face culling setGraphicsState(HKG_ENABLED_CULLFACE, false); // don't really want shadows as makes it too dark forceShadowState(false); setupLights(m_env); // so that the extra lights are added // allow color change on precreated objects m_env->m_displayHandler->setAllowColorChangeOnPrecreated(true); } // Create the world { hkpWorldCinfo info; info.setBroadPhaseWorldSize( 350.0f ); info.m_gravity.set(0,0,-9.8f); info.m_collisionTolerance = 0.01f; m_world = new hkpWorld( info ); m_world->lock(); hkpAgentRegisterUtil::registerAllAgents(m_world->getCollisionDispatcher()); setupGraphics(); } // Load the level { m_loader = new hkLoader(); hkString assetFile = hkAssetManagementUtil::getFilePath("Resources/Physics/levels/test_platform.hkx"); hkRootLevelContainer* container = m_loader->load( assetFile.cString() ); HK_ASSERT2(0x27343437, container != HK_NULL , "Could not load asset"); hkxScene* scene = reinterpret_cast<hkxScene*>( container->findObjectByType( hkxSceneClass.getName() )); HK_ASSERT2(0x27343635, scene, "No scene loaded"); env->m_sceneConverter->convert( scene, hkgAssetConverter::CONVERT_ALL ); hkpPhysicsData* physics = reinterpret_cast<hkpPhysicsData*>( container->findObjectByType( hkpPhysicsDataClass.getName() )); HK_ASSERT2(0x27343635, physics, "No physics loaded"); // Physics if (physics) { const hkArray<hkpPhysicsSystem*>& psys = physics->getPhysicsSystems(); // Tie the two together for (int i=0; i<psys.getSize(); i++) { hkpPhysicsSystem* system = psys[i]; // Change the layer of the rigid bodies for (int rb=0; rb < system->getRigidBodies().getSize(); rb++) { const hkUlong id = hkUlong(system->getRigidBodies()[rb]->getCollidable()); HK_SET_OBJECT_COLOR(id,NORMAL_GRAY); m_objectIds.pushBack(id); } // Associate the display and physics (by name) if (scene) { addPrecreatedDisplayObjectsByName( psys[i]->getRigidBodies(), scene ); } // add the lot to the world m_world->addPhysicsSystem(system); } } } // Add horizontal keyframed platform { hkpShape* platform = new hkpBoxShape(hkVector4(1.5,2.5,0.25)); hkpRigidBodyCinfo rbci; rbci.m_shape = platform; rbci.m_motionType = hkpMotion::MOTION_KEYFRAMED; rbci.m_position.set(2.5f, 0.0f, 0.25f); rbci.m_friction = 1.0f; rbci.m_collisionFilterInfo = hkpGroupFilter::calcFilterInfo(hkpGroupFilter::calcFilterInfo(1)); m_horPlatform = new hkpRigidBody(rbci); platform->removeReference(); m_world->addEntity(m_horPlatform); m_horPlatform->removeReference(); } // Add vertical keyframed platform { hkpShape* platform = new hkpBoxShape(hkVector4(1.5,2.5,0.25)); hkpRigidBodyCinfo rbci; rbci.m_shape = platform; rbci.m_motionType = hkpMotion::MOTION_KEYFRAMED; rbci.m_position.set(-3.5f, 0.0f, 3.25f); rbci.m_friction = 1.0f; rbci.m_collisionFilterInfo = hkpGroupFilter::calcFilterInfo(hkpGroupFilter::calcFilterInfo(1)); m_verPlatform = new hkpRigidBody(rbci); platform->removeReference(); m_world->addEntity(m_verPlatform); m_verPlatform->removeReference(); } // Create a character rigid body { // Create a capsule to represent the character standing hkVector4 vertexA(0,0, 0.4f); hkVector4 vertexB(0,0,-0.4f); m_standShape = new hkpCapsuleShape(vertexA, vertexB, .6f); // Construct a character rigid body hkpCharacterRigidBodyCinfo info; info.m_mass = 100.0f; info.m_shape = m_standShape; info.m_maxForce = 1000.0f; info.m_up = UP; info.m_position.set(0.0f, 5.0f, 1.5f); info.m_maxSlope = HK_REAL_PI/2.0f; m_characterRigidBody = new hkpCharacterRigidBody( info ); m_world->addEntity( m_characterRigidBody->getRigidBody() ); } // Create the character state machine { hkpCharacterState* state; hkpCharacterStateManager* manager = new hkpCharacterStateManager(); state = new hkpCharacterStateOnGround(); manager->registerState( state, HK_CHARACTER_ON_GROUND); state->removeReference(); state = new hkpCharacterStateInAir(); manager->registerState( state, HK_CHARACTER_IN_AIR); state->removeReference(); state = new hkpCharacterStateJumping(); manager->registerState( state, HK_CHARACTER_JUMPING); state->removeReference(); state = new hkpCharacterStateClimbing(); manager->registerState( state, HK_CHARACTER_CLIMBING); state->removeReference(); m_characterContext = new hkpCharacterContext(manager, HK_CHARACTER_ON_GROUND); m_characterContext->setCharacterType(hkpCharacterContext::HK_CHARACTER_RIGIDBODY); manager->removeReference(); } // Set colors of platforms HK_SET_OBJECT_COLOR(hkUlong(m_verPlatform->getCollidable()),hkColor::BLUE); HK_SET_OBJECT_COLOR(hkUlong(m_horPlatform->getCollidable()),hkColor::GREEN); // Set global time m_time = 0.0f; // Initialize hkpSurfaceInfo for previous ground m_previousGround = new hkpSurfaceInfo(); m_framesInAir = 0; // Current camera angle about up m_currentAngle = HK_REAL_PI * 0.5f; m_world->unlock(); }
OBJScene::OBJScene() { setupCamera(); setupObjects(); setupLights(); }
void TransIcelandicExpress::redraw( void ) { static tex_init = 0; if (!tex_init) { ilutRenderer( ILUT_OPENGL ); ilGenImages( 1, &ImageName ); ilBindImage( ImageName ); glEnable( GL_TEXTURE_2D ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); if (!ilLoadImage( "ludum48.png" )) { printf("Loading image failed\n"); } gl_tex_id = ilutGLBindTexImage(); ilutGLTexImage( 0 ); tex_init = 1; } glBindTexture (GL_TEXTURE_2D, gl_tex_id ); glClearColor( 0.3f, 0.4f, 0.6f, 1.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); //glEnable( GL_CULL_FACE ); glEnable( GL_DEPTH_TEST ); // 3d part glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 60.0, 800.0/600.0, 0.05, 100.0 ); gluLookAt( player->pos[0]+cameraPos[0], player->pos[1]+cameraPos[1]+c_PlayerHeight, player->pos[2]+cameraPos[2], player->pos[0], player->pos[1]+ c_PlayerHeight, player->pos[2], 0.0, 1.0, 0.0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); // apply some of the camera xform to the light just to make // it more shiny glPushMatrix(); float viewHead = atan2( cameraPos[2], cameraPos[0] ); glRotated( viewHead * SG_RADIANS_TO_DEGREES, 0.0f, 1.0f, 0.0f ); setupLights(); glPopMatrix(); draw3d(); // 2d part glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluOrtho2D( 0, 800, 0, 600 ) ; glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glDisable( GL_LIGHTING ); draw2d(); SDL_GL_SwapBuffers(); }