void MyApp::renderScene() { static float time = 0.0f; if (!m_bPaused) time += 0.001f; // Clear the back buffer float clearColor[3] = { 0.4f, 0.4f, 0.7f }; float clearColorBlack[3] = { 0.f, 0.f, 0.f }; _dxImmedDC->ClearRenderTargetView(_renderTargetView, (float*)&clearColorBlack); _dxImmedDC->ClearDepthStencilView(_depthStencilView, D3D11_CLEAR_DEPTH, 1, 0); _dxImmedDC->OMSetBlendState(0, 0, 0xffffffff); _dxImmedDC->RSSetState(0); // Bind the input layout _dxImmedDC->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); XMMATRIX mVP = m_camera.getViewMatrix()*m_camera.getProjectionMatrix(); //_______I m p l i c i t O b j e c t s_____________ drawImplicitToTexture(); setMatrixVar(m_fxQuads, (void*)&mVP, "mViewProj"); setSrvArrayVar(m_fxQuads, &m_srvImplicit, "texarrObjects", 0, 5); _dxImmedDC->IASetInputLayout(0); _dxImmedDC->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST); ID3DX11EffectTechnique* tech; tech = m_fxQuads->GetTechniqueByIndex(0); tech->GetPassByIndex(0)->Apply(0, _dxImmedDC); _dxImmedDC->Draw(4, 0); //_______T e s s e l l a t e d O b j e c t s _______ if (glb_bWireframe) _dxImmedDC->RSSetState(rs_Wireframe); // Scene - Spheres for (unsigned int i=0; i<m_spheres.size(); i++) { drawTessSphereFromOct(&(m_spheres[i])); } myAlien.setPos(0,30,0); if (myAlien.type == AlienTypes::GS_ALIEN) drawMesh(myAlien.mesh, m_fxAlienGS, myAlien.getMatrix()); else if (myAlien.type == AlienTypes::EXP_ALIEN) { drawMesh(myAlien.mesh, m_fxExplosion, myAlien.getMatrix(), myAlien.expl_time); myAlien.expl_time += 0.001f; } XMFLOAT4X4 mI; XMStoreFloat4x4(&mI, XMMatrixIdentity()); // Scene - Aliens for (unsigned int i=0; i<m_aliens.size(); i++) { if (m_aliens[i].type == AlienTypes::VS_ALIEN) drawMesh(m_aliens[i].mesh, m_fxAlienVS, m_aliens[i].getMatrix()); else if (m_aliens[i].type == AlienTypes::GS_ALIEN) drawMesh(m_aliens[i].mesh, m_fxAlienGS, m_aliens[i].getMatrix()); else if (m_aliens[i].type == AlienTypes::HS_ALIEN) drawTessMesh(m_aliens[i].getMatrix()); else if (m_aliens[i].type == AlienTypes::EXP_ALIEN) { drawMesh(m_aliens[i].mesh, m_fxExplosion, m_aliens[i].getMatrix(), m_aliens[i].expl_time); m_aliens[i].expl_time += 0.001f; } else if (m_aliens[i].type == AlienTypes::BEZ_ALIEN) // BEZ_ALIEN drawTessBezierSurface(m_aliens[i].getPos(), m_aliens[i].getTargetPos()); else // PSP_ALIEN drawPSPSurface(m_aliens[i].getPos(), m_aliens[i].getTargetPos()); } // PSP Surface if (glb_bSphereMesh) drawTessSphereFromMesh(); // Terrain editTerrain(); drawTessTerrain(); //_______ G U I ______________________________________ TwDraw(); // Swap Buffer _swapChain->Present(0, 0); }
// Main int main() { GLFWvidmode mode; // GLFW video mode TwBar *bar; // Pointer to a tweak bar double time = 0, dt;// Current time and enlapsed time double turn = 0; // Model turn counter double speed = 0.3; // Model rotation speed int wire = 0; // Draw model in wireframe? float bgColor[] = { 0.1f, 0.2f, 0.4f }; // Background color unsigned char cubeColor[] = { 255, 0, 0, 128 }; // Model color (32bits RGBA) // Intialize GLFW if( !glfwInit() ) { // An error occured fprintf(stderr, "GLFW initialization failed\n"); return 1; } // Create a window glfwGetDesktopMode(&mode); if( !glfwOpenWindow(640, 480, mode.RedBits, mode.GreenBits, mode.BlueBits, 0, 16, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) ) { // A fatal error occured fprintf(stderr, "Cannot open GLFW window\n"); glfwTerminate(); return 1; } glfwEnable(GLFW_MOUSE_CURSOR); glfwEnable(GLFW_KEY_REPEAT); glfwSetWindowTitle("AntTweakBar simple example using GLFW"); // Initialize AntTweakBar TwInit(TW_OPENGL, NULL); // Create a tweak bar bar = TwNewBar("TweakBar"); TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar. // Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S]. TwAddVarRW(bar, "speed", TW_TYPE_DOUBLE, &speed, " label='Rot speed' min=0 max=2 step=0.01 keyIncr=s keyDecr=S help='Rotation speed (turns/second)' "); // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w]. TwAddVarRW(bar, "wire", TW_TYPE_BOOL32, &wire, " label='Wireframe mode' key=w help='Toggle wireframe display mode.' "); // Add 'time' to 'bar': it is a read-only (RO) variable of type TW_TYPE_DOUBLE, with 1 precision digit TwAddVarRO(bar, "time", TW_TYPE_DOUBLE, &time, " label='Time' precision=1 help='Time (in seconds).' "); // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color) TwAddVarRW(bar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' "); // Add 'cubeColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR32 (32 bits color) with alpha TwAddVarRW(bar, "cubeColor", TW_TYPE_COLOR32, &cubeColor, " label='Cube color' alpha help='Color and transparency of the cube.' "); // Set GLFW event callbacks // - Redirect window size changes to the callback function WindowSizeCB glfwSetWindowSizeCallback(WindowSizeCB); // - Directly redirect GLFW mouse button events to AntTweakBar glfwSetMouseButtonCallback((GLFWmousebuttonfun)TwEventMouseButtonGLFW); // - Directly redirect GLFW mouse position events to AntTweakBar glfwSetMousePosCallback((GLFWmouseposfun)TwEventMousePosGLFW); // - Directly redirect GLFW mouse wheel events to AntTweakBar glfwSetMouseWheelCallback((GLFWmousewheelfun)TwEventMouseWheelGLFW); // - Directly redirect GLFW key events to AntTweakBar glfwSetKeyCallback((GLFWkeyfun)TwEventKeyGLFW); // - Directly redirect GLFW char events to AntTweakBar glfwSetCharCallback((GLFWcharfun)TwEventCharGLFW); // Initialize time time = glfwGetTime(); // Main loop (repeated while window is not closed and [ESC] is not pressed) while( glfwGetWindowParam(GLFW_OPENED) && !glfwGetKey(GLFW_KEY_ESC) ) { // Clear frame buffer using bgColor glClearColor(bgColor[0], bgColor[1], bgColor[2], 1); glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); // Rotate model dt = glfwGetTime() - time; if( dt < 0 ) dt = 0; time += dt; turn += speed*dt; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotated(360.0*turn, 0.4, 1, 0.2); glTranslated(-0.5, -0.5, -0.5); // Set color and draw model glColor4ubv(cubeColor); DrawModel(wire); // Draw tweak bars TwDraw(); // Present frame buffer glfwSwapBuffers(); } // Terminate AntTweakBar and GLFW TwTerminate(); glfwTerminate(); return 0; }
int main(void) { Context ctx; // Create a GLFW window glfwSetErrorCallback(errorCallback); glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); ctx.width = 800; ctx.height = 600; ctx.aspect = float(ctx.width) / float(ctx.height); ctx.window = glfwCreateWindow(ctx.width, ctx.height, "Model viewer", nullptr, nullptr); glfwMakeContextCurrent(ctx.window); glfwSetWindowUserPointer(ctx.window, &ctx); glfwSetKeyCallback(ctx.window, keyCallback); glfwSetMouseButtonCallback(ctx.window, mouseButtonCallback); glfwSetCursorPosCallback(ctx.window, cursorPosCallback); glfwSetScrollCallback(ctx.window, scrollCallback); glfwSetFramebufferSizeCallback(ctx.window, resizeCallback); // Load OpenGL functions glewExperimental = true; GLenum status = glewInit(); if (status != GLEW_OK) { std::cerr << "Error: " << glewGetErrorString(status) << std::endl; std::exit(EXIT_FAILURE); } std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; // Initialize AntTweakBar (if enabled) #ifdef WITH_TWEAKBAR TwInit(TW_OPENGL_CORE, nullptr); TwWindowSize(ctx.width, ctx.height); TwBar *tweakbar = TwNewBar("Settings"); TwDefine("Settings size='300 500'"); TwDefine("Settings refresh=0.1"); TwDefine("Settings valueswidth=fit"); TwEnumVal lensEV[] = { {ORTOGRAPHIC, "Orthographic"}, {PERSPECTIVE, "Perspective"} }; TwType lensType = TwDefineEnum("LensType", lensEV, 2); TwAddVarRW(tweakbar, "Lens / Projection", lensType, &ctx.lensType, NULL); TwAddSeparator(tweakbar, NULL, NULL); TwAddVarRW(tweakbar, "Background color", TW_TYPE_COLOR3F, &ctx.background_color[0], "colormode=hls"); TwAddSeparator(tweakbar, NULL, NULL); TwAddVarRW(tweakbar, "Ambient light color", TW_TYPE_COLOR3F, &ctx.ambient_light[0], "colormode=hls"); TwAddVarRW(tweakbar, "Point light color", TW_TYPE_COLOR3F, &ctx.light_color[0], "colormode=hls"); TwAddVarRW(tweakbar, "Point light position", TW_TYPE_DIR3F, &ctx.light_position[0], NULL); //TwAddVarRW(tweakbar, "Point light x", TW_TYPE_FLOAT, &ctx.light_position[0], NULL); //TwAddVarRW(tweakbar, "Point light y", TW_TYPE_FLOAT, &ctx.light_position[1], NULL); //TwAddVarRW(tweakbar, "Point light z", TW_TYPE_FLOAT, &ctx.light_position[2], NULL); TwAddSeparator(tweakbar, NULL, NULL); TwAddVarRW(tweakbar, "Material diffuse color", TW_TYPE_COLOR3F, &ctx.diffuse_color[0], "colormode=hls"); TwAddVarRW(tweakbar, "Material specular color", TW_TYPE_COLOR3F, &ctx.specular_color[0], "colormode=hls"); TwAddVarRW(tweakbar, "Material specular power", TW_TYPE_FLOAT, &ctx.specular_power, NULL); TwAddSeparator(tweakbar, NULL, NULL); TwEnumVal colorModeEV[] = { {NORMAL_AS_RGB, "Normal as RGB"}, {BLINN_PHONG, "Blinn-Phong"}, {REFLECTION, "Reflection"} }; TwType colorModeType = TwDefineEnum("ColorMode", colorModeEV, ColorMode::SIZE); TwAddVarRW(tweakbar, "Color mode", colorModeType, &ctx.color_mode, NULL); TwAddVarRW(tweakbar, "Use gamma correction", TW_TYPE_BOOL32, &ctx.use_gamma_correction, NULL); TwAddVarRW(tweakbar, "Use color inversion", TW_TYPE_BOOL32, &ctx.use_color_inversion, NULL); TwAddSeparator(tweakbar, NULL, NULL); TwAddVarRW(tweakbar, "Ambient weight", TW_TYPE_FLOAT, &ctx.ambient_weight, NULL); TwAddVarRW(tweakbar, "Diffuse weight", TW_TYPE_FLOAT, &ctx.diffuse_weight, NULL); TwAddVarRW(tweakbar, "Specular weight", TW_TYPE_FLOAT, &ctx.specular_weight, NULL); #endif // WITH_TWEAKBAR // Initialize rendering glGenVertexArrays(1, &ctx.defaultVAO); glBindVertexArray(ctx.defaultVAO); glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); init(ctx); // Start rendering loop while (!glfwWindowShouldClose(ctx.window)) { glfwPollEvents(); ctx.elapsed_time = glfwGetTime(); display(ctx); #ifdef WITH_TWEAKBAR TwDraw(); #endif // WITH_TWEAKBAR glfwSwapBuffers(ctx.window); } // Shutdown #ifdef WITH_TWEAKBAR TwTerminate(); #endif // WITH_TWEAKBAR glfwDestroyWindow(ctx.window); glfwTerminate(); std::exit(EXIT_SUCCESS); }
// ----------------------------------------------------------- build_buffer --- void build_buffer( void ) { vec2 pen; size_t i; texture_font_t *font; texture_glyph_t *glyph; vec4 white = {{1.0, 1.0, 1.0, 1.0}}; vec4 none = {{1.0, 1.0, 1.0, 0.0}}; markup_t markup = { .family = "Arial", .size = 10.0, .bold = 0, .italic = 0, .rise = 0.0, .spacing = 0.0, .gamma = 2.2, .foreground_color = white, .background_color = none, .underline = 0, .underline_color = white, .overline = 0, .overline_color = white, .strikethrough = 0, .strikethrough_color = white, .font = 0, }; vertex_buffer_clear( buffer ); texture_atlas_clear( atlas ); if( p_family == VERA) { font = texture_font_new( atlas, "fonts/Vera.ttf", p_size ); } else if( p_family == VERA_MONO) { font = texture_font_new( atlas, "fonts/VeraMono.ttf", p_size ); } else if( p_family == GEORGIA) { font = texture_font_new( atlas, "fonts/Georgia.ttf", p_size ); } else if( p_family == TIMES ) { font = texture_font_new( atlas, "fonts/Times.ttf", p_size ); } else if( p_family == TAHOMA ) { font = texture_font_new( atlas, "fonts/Tahoma.ttf", p_size ); } else if( p_family == ARIAL ) { font = texture_font_new( atlas, "fonts/Arial.ttf", p_size ); } else if( p_family == VERDANA ) { font = texture_font_new( atlas, "fonts/Verdana.ttf", p_size ); } else { fprintf( stderr, "Error : Unknown family type\n" ); return; } font->hinting = p_hinting; font->filtering = 1; float norm = 1.0/(p_primary + 2*p_secondary + 2*p_tertiary); font->lcd_weights[0] = (unsigned char)(p_tertiary*norm*256); font->lcd_weights[1] = (unsigned char)(p_secondary*norm*256); font->lcd_weights[2] = (unsigned char)(p_primary*norm*256); font->lcd_weights[3] = (unsigned char)(p_secondary*norm*256); font->lcd_weights[4] = (unsigned char)(p_tertiary*norm*256); texture_font_load_glyphs( font, L" !\"#$%&'()*+,-./0123456789:;<=>?" L"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" L"`abcdefghijklmnopqrstuvwxyz{|}~" ); pen.x = 10; pen.y = 600 - font->height - 10; glyph = texture_font_get_glyph( font, text[0] ); add_glyph( glyph, buffer, &markup, &pen, 0 ); for( i=1; i<wcslen(text); ++i ) { if( text[i] == '\n' ) { pen.x = 10; pen.y -= font->height; // + 0.01*(size - (int)size)*font->height; } else { glyph = texture_font_get_glyph( font, text[i] ); float kerning = 0.0; if( p_kerning ) { kerning = texture_glyph_get_kerning( glyph, text[i-1] ); } add_glyph( glyph, buffer, &markup, &pen, kerning ); } } texture_font_delete (font ); } // ---------------------------------------------------------------- display --- void display(void) { if( p_invert ) { glClearColor( 0, 0, 0, 1 ); } else { glClearColor( 1, 1, 1, 1 ); } glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, atlas->id ); if( !p_lcd_filtering ) { glEnable( GL_COLOR_MATERIAL ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); if( p_invert ) { glColor4f(1,1,1,1); } else { glColor4f(0,0,0,1); } } else { glEnable( GL_COLOR_MATERIAL ); glBlendFunc( GL_CONSTANT_COLOR_EXT, GL_ONE_MINUS_SRC_COLOR ); glEnable( GL_BLEND ); glColor3f( 1,1,1 ); if( p_invert ) { glBlendColor( 1, 1, 1, 1 ); } else { glBlendColor( 0, 0, 0, 1 ); } } if( !p_lcd_filtering ) { vertex_buffer_render( buffer, GL_TRIANGLES, "vt" ); } else { glUseProgram( program ); glUniform1i( texture_location, 0 ); glUniform1f( gamma_location, p_gamma ); float norm = 1.0/(p_primary+2*p_secondary+2*p_tertiary); glUniform1f( primary_location, p_primary*norm ); glUniform1f( secondary_location, p_secondary*norm ); glUniform1f( tertiary_location, p_tertiary*norm ); glUniform2f( pixel_location, 1.0/atlas->width, 1.0/atlas->height ); vertex_buffer_render( buffer, GL_TRIANGLES, "vtc" ); glUseProgram( 0 ); } TwDraw( ); glutSwapBuffers( ); } // ---------------------------------------------------------------- reshape --- void reshape( int width, int height ) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, width, 0, height, -1, 1); glMatrixMode(GL_MODELVIEW); TwWindowSize( width, height ); }
void TweakBar::Render() { TwDraw(); }
// ----------------------------------------------------------- build_buffer --- void build_buffer( void ) { vec2 pen; texture_font_t *font; vec4 black = {{0.0, 0.0, 0.0, 1.0}}; vec4 white = {{1.0, 1.0, 1.0, 1.0}}; vec4 none = {{1.0, 1.0, 1.0, 0.0}}; vec4 color = white; if( p_invert ) { color = black; } markup_t markup = { .family = "Source Sans Pro", .size = 10.0, .bold = 0, .italic = 0, .rise = 0.0, .spacing = p_interval, .gamma = p_gamma, .foreground_color = color, .background_color = none, .underline = 0, .underline_color = color, .overline = 0, .overline_color = color, .strikethrough = 0, .strikethrough_color = color, .font = 0, }; text_buffer_clear( buffer ); texture_atlas_t * atlas = buffer->manager->atlas; texture_atlas_clear( atlas ); if( p_family == VERA) { font = texture_font_new_from_file( atlas, p_size, "fonts/Vera.ttf" ); } else if( p_family == VERA_MONO) { font = texture_font_new_from_file( atlas, p_size, "fonts/VeraMono.ttf" ); } else if( p_family == LUCKIEST_GUY) { font = texture_font_new_from_file( atlas, p_size, "fonts/LuckiestGuy.ttf" ); } else if( p_family == SOURCE_SANS ) { font = texture_font_new_from_file( atlas, p_size, "fonts/SourceSansPro-Regular.ttf" ); } else if( p_family == SOURCE_CODE ) { font = texture_font_new_from_file( atlas, p_size, "fonts/SourceCodePro-Regular.ttf" ); } else if( p_family == OLD_STANDARD ) { font = texture_font_new_from_file( atlas, p_size, "fonts/OldStandard-Regular.ttf" ); } else if( p_family == LOBSTER ) { font = texture_font_new_from_file( atlas, p_size, "fonts/Lobster-Regular.ttf" ); } else { fprintf( stderr, "Error : Unknown family type\n" ); return; } if (!font) return; markup.font = font; font->hinting = p_hinting; font->kerning = p_kerning; font->filtering = 1; float norm = 1.0/(p_primary + 2*p_secondary + 2*p_tertiary); font->lcd_weights[0] = (unsigned char)(p_tertiary*norm*256); font->lcd_weights[1] = (unsigned char)(p_secondary*norm*256); font->lcd_weights[2] = (unsigned char)(p_primary*norm*256); font->lcd_weights[3] = (unsigned char)(p_secondary*norm*256); font->lcd_weights[4] = (unsigned char)(p_tertiary*norm*256); pen.x = 10; pen.y = 600 - font->height - 10; text_buffer_printf( buffer, &pen, &markup, text, NULL ); // Post-processing for width and orientation vertex_buffer_t * vbuffer = buffer->buffer; size_t i; for( i=0; i < vector_size( vbuffer->items ); ++i ) { ivec4 *item = (ivec4 *) vector_get( vbuffer->items, i); glyph_vertex_t * v0 = /* x0,y0 */ (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+0 ); //glyph_vertex_t * v1 = /* x0,y1 */ // (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+1 ); glyph_vertex_t * v2 = /* x1,y1 */ (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+2 ); glyph_vertex_t * v3 = /* x1,y0 */ (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+3 ); float x0 = v0->x, y0 = v0->y; float x1 = v2->x, y1 = v2->y; v2->x = v3->x = x0 + (x1-x0)*p_width; float dy = abs(y1-y0); float dx = tan(p_faux_italic/180.0 * M_PI) * dy; v0->x += dx; v0->shift = fmod(v0->shift + dx-(int)(dx),1.0); v3->x += dx; v3->shift = fmod(v3->shift + dx-(int)(dx),1.0); } texture_font_delete( font ); } // ---------------------------------------------------------------- display --- void display( GLFWwindow* window ) { vec4 black = {{0.0, 0.0, 0.0, 1.0}}; vec4 white = {{1.0, 1.0, 1.0, 1.0}}; if( !p_invert ) { glClearColor( 0, 0, 0, 1 ); buffer->base_color = white; } else { glClearColor( 1, 1, 1, 1 ); buffer->base_color = black; } glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glUseProgram( buffer->shader ); { glUniformMatrix4fv( glGetUniformLocation( buffer->shader, "model" ), 1, 0, model.data); glUniformMatrix4fv( glGetUniformLocation( buffer->shader, "view" ), 1, 0, view.data); glUniformMatrix4fv( glGetUniformLocation( buffer->shader, "projection" ), 1, 0, projection.data); text_buffer_render( buffer ); } TwDraw( ); glfwSwapBuffers( window ); }
// ********************************************************** Figure::render void render( bool update_axes_x=false, bool update_axes_y=false ) { glfwMakeContextCurrent( _window ); // TODO can also be set to another DataStructure glfwSetWindowUserPointer( _window, this); if( _offscreen ) { // set rendering destination to FBO glBindFramebuffer(GL_FRAMEBUFFER, _fbo); utils::gl::check_error(); } if( update_axes_x || update_axes_y ) { // Build proper axis by finding min/max on each axe BoundingBox bbox{ std::numeric_limits<double>::max(), (-std::numeric_limits<double>::max()), std::numeric_limits<double>::max(), -std::numeric_limits<double>::max() }; for( const auto& curve: _curves ) { auto b = curve->get_bbox(); if( b.x_min < bbox.x_min ) bbox.x_min = b.x_min; if( b.x_max > bbox.x_max ) bbox.x_max = b.x_max; if( b.y_min < bbox.y_min ) bbox.y_min = b.y_min; if( b.y_max > bbox.y_max ) bbox.y_max = b.y_max; } if( update_axes_x) _axis_x = Axis( "X", {bbox.x_min,bbox.x_max, 10, 2}); if( update_axes_y ) _axis_y = Axis( "Y", {bbox.y_min,bbox.y_max, 10, 2}); } // get window size if( _offscreen ) { glBindRenderbuffer( GL_RENDERBUFFER, _render_buf ); utils::gl::check_error(); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &_width); glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &_height); utils::gl::check_error(); glBindRenderbuffer( GL_RENDERBUFFER, 0 ); utils::gl::check_error(); } else { glfwGetFramebufferSize( _window, &_width, &_height); } // Info for scaling View and axes auto x_min_win = _axis_x.get_range()._min - 0.08 * (_axis_x.get_range()._max - _axis_x.get_range()._min); auto x_max_win = _axis_x.get_range()._max + 0.08 * (_axis_x.get_range()._max - _axis_x.get_range()._min); auto ratio_x = (x_max_win-x_min_win) / (double) _width; auto y_min_win = _axis_y.get_range()._min - 0.08 * (_axis_y.get_range()._max - _axis_y.get_range()._min); auto y_max_win = _axis_y.get_range()._max + 0.08 * (_axis_y.get_range()._max - _axis_y.get_range()._min); auto ratio_y = (y_max_win-y_min_win) / (double) _height; glViewport(0, 0, _width, _height); glClearColor( 1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho( x_min_win, x_max_win, y_min_win, y_max_win, 1.f, -1.f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Basic axes if( _draw_axes ) { _axis_x.render( ratio_x, ratio_y ); glPushMatrix(); // AXE_Y glRotated( 90.0, 0.0, 0.0, 1.0 ); _axis_y.render( ratio_y, ratio_x); glPopMatrix(); // AXE_Y } // All other objects for( const auto& curve: _curves) { curve->render(); } // GraphicText for( auto& txt: _text_list) { glPushMatrix(); { glTranslated( txt.x, txt.y, 0.0); glScaled( ratio_x, ratio_y, 1.0 ); _font->Render( txt.msg.c_str() ); } glPopMatrix(); } if( not _offscreen ) { // Draw tweak bars TwDraw(); glfwSwapBuffers( _window ); glfwPollEvents(); } }
int main (int argc, const char * argv[]) { // initialise GLFW int running = GL_TRUE; if (!glfwInit()) { exit(EXIT_FAILURE); } glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1); GLFWvidmode mode; glfwGetDesktopMode(&mode); if( !glfwOpenWindow(windowWidth, windowHeight, mode.RedBits, mode.GreenBits, mode.BlueBits, 0, 32, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) ) { glfwTerminate(); exit(EXIT_FAILURE); } glfwEnable(GLFW_MOUSE_CURSOR); glfwEnable(GLFW_KEY_REPEAT); // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); glfwSetMousePos(windowWidth/2, windowHeight/2); glfwSetWindowTitle("basic Cube with GUI"); //init GLEW and basic OpenGL information // VERY IMPORTANT OTHERWISE GLEW CANNOT HANDLE GL3 #ifdef USE_OPENGL32 glewExperimental = true; #endif glewInit(); std::cout<<"\nUsing GLEW "<<glewGetString(GLEW_VERSION)<<std::endl; if (GLEW_VERSION_3_2) { std::cout<<"Yay! OpenGL 3.2 is supported and GLSL 1.5!\n"<<std::endl; } if (glewIsSupported("GL_ARB_vertex_buffer_object")) std::cout<<"ARB VBO's are supported"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_buffer_object")) std::cout<<"APPLE VBO's are supported"<<std::endl; else std::cout<<"VBO's are not supported,program will not run!!!"<<std::endl; if (glewIsSupported("GL_ARB_vertex_array_object")) std::cout<<"ARB VAO's are supported\n"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_array_object"))//this is the name of the extension for GL2.1 in MacOSX std::cout<<"APPLE VAO's are supported\n"<<std::endl; else std::cout<<"VAO's are not supported, program will not run!!!\n"<<std::endl; std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl; std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl; std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl; //init AntTweakBar TwInit(TW_OPENGL_CORE, NULL); //OpenGL 3.2 // Set GLFW event callbacks // - Redirect window size changes to the callback function WindowSizeCB glfwSetWindowSizeCallback(WindowSizeCB); // - Directly redirect GLFW mouse button events to AntTweakBar //glfwSetMouseButtonCallback((GLFWmousebuttonfun)TwEventMouseButtonGLFW); glfwSetMouseButtonCallback(OnMouseButton); // - Directly redirect GLFW mouse position events to AntTweakBar //glfwSetMousePosCallback((GLFWmouseposfun)TwEventMousePosGLFW); glfwSetMousePosCallback(OnMousePos); // - Directly redirect GLFW mouse wheel events to AntTweakBar //glfwSetMouseWheelCallback((GLFWmousewheelfun)TwEventMouseWheelGLFW); glfwSetMouseWheelCallback(OnMouseWheel); // - Directly redirect GLFW key events to AntTweakBar //glfwSetKeyCallback((GLFWkeyfun)TwEventKeyGLFW); glfwSetKeyCallback(OnKey); // - Directly redirect GLFW char events to AntTweakBar //glfwSetCharCallback((GLFWcharfun)TwEventCharGLFW); glfwSetCharCallback(OnChar); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); checkOpenGLError(__FILE__, __LINE__); // init Scene initScene(); //Create tweak bars GUI TwWindowSize(windowWidth, windowHeight); myBar = TwNewBar("myBar"); // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w]. TwAddVarRW(myBar, "wire", TW_TYPE_BOOL32, &wireFrame, " label='Wireframe mode' key=w help='Toggle wireframe display mode.' "); TwAddVarRW(myBar, "useglm", TW_TYPE_BOOL32, &UseGLMMatrices , " label='Use GLM' key=g help='Toggle using GLM for matrices.' "); TwAddVarRW(myBar, "autorotate", TW_TYPE_BOOL32, &autoRotate , " label='AutoRotate' key=r help='Toggle autorotation.' "); // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color) //TwAddVarRW(myBar, "bgColor", TW_TYPE_COLOR4F, &bgColor, " label='Background color' "); TwAddVarRW(myBar, "bgColor", TW_TYPE_COLOR4F, glm::value_ptr(bgColor), " label='Background color' "); TwAddVarRW(myBar, "fx", TW_TYPE_FLOAT, &fx , " min=0 max=1000 step=0.5 "); TwAddVarRW(myBar, "fy", TW_TYPE_FLOAT, &fy , " min=0 max=1000 step=0.5 "); TwAddVarRW(myBar, "near", TW_TYPE_FLOAT, &near , " min=0 max=1000 step=0.5 "); TwAddVarRW(myBar, "far", TW_TYPE_FLOAT , &far , " min=0 max=1000 step=0.5 "); TwAddVarRW(myBar, "CameraX", TW_TYPE_FLOAT, &camera.pos[0] , " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "CameraY", TW_TYPE_FLOAT, &camera.pos[1], " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "CameraZ", TW_TYPE_FLOAT, &camera.pos[2], " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "LookX", TW_TYPE_FLOAT, &cameraLookAt.pos[0] , " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "LookY", TW_TYPE_FLOAT, &cameraLookAt.pos[1], " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "LookZ", TW_TYPE_FLOAT, &cameraLookAt.pos[2], " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "Camera Rotation", TW_TYPE_QUAT4F, &camera.angle, ""); TwAddVarRW(myBar, "LightX", TW_TYPE_FLOAT, &lightPosition[0] , " min=-20 max=30 step=0.5 "); TwAddVarRW(myBar, "LightY", TW_TYPE_FLOAT, &lightPosition[1] , " min=-20 max=30 step=0.5 "); TwAddVarRW(myBar, "LightZ", TW_TYPE_FLOAT, &lightPosition[2] , " min=-20 max=30 step=0.5 "); TwAddVarRW(myBar, "lightColor", TW_TYPE_COLOR4F, lightColor, " label='Light color ' "); TwAddVarRW(myBar, "MaterialAmbient", TW_TYPE_FLOAT, &lightMaterials[0] , " min=0 max=1.0 step=0.1 "); TwAddVarRW(myBar, "MaterialDiffuse", TW_TYPE_FLOAT, &lightMaterials[1] , " min=0 max=1.0 step=0.1 "); TwAddVarRW(myBar, "MaterialSpecular", TW_TYPE_FLOAT, &lightMaterials[2] , " min=0 max=1.0 step=0.1 "); TwAddVarRW(myBar, "fogColor", TW_TYPE_COLOR4F, fogColorAndScale, " label='Fog color and intensity' "); //TwDefine("myBar alwaystop=true "); // mybar is always on top //GLFW main loop while (running) { glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); glClearColor( bgColor.r,bgColor.g,bgColor.b,bgColor.a); checkOpenGLError(__FILE__, __LINE__); // call function to render our scene drawScene(); //restore FILL mode (we don't want the GUI to be drawn in 'wireframe') glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); checkOpenGLError(__FILE__, __LINE__); TwDraw(); checkOpenGLError(__FILE__, __LINE__); glfwSwapBuffers(); //check if ESC was pressed running=!glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED); } //terminate AntTweakBar TwTerminate(); //cleanup VAO, VBO and shaders glDeleteBuffers(1,&buffer); glDeleteProgram(program); glDeleteVertexArrays(1,&vao); //close OpenGL window and terminate GLFW glfwTerminate(); exit(EXIT_SUCCESS); }
// Callback function called by GLUT to render screen void Display(void) { // Clear frame buffer glClearColor(0.7, 0.7, 0.7, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glEnable(GL_NORMALIZE); float lightPositon[4]; float l = sqrtf(powf(lightDirection[0], 2) + powf(lightDirection[1], 2) + powf(lightDirection[2], 2)); lightPositon[0] = -lightDistance*lightDirection[0] / l; lightPositon[1] = -lightDistance*lightDirection[1] / l; lightPositon[2] = -lightDistance*lightDirection[2] / l; lightPositon[3] = 1.0f; // point light glUseProgram(0); glPushMatrix(); glTranslatef(0.5f, -0.3f, 0.0f); if (g_AutoRotate) { float axis[3] = { 0, 1, 0 }; float angle = (float)(GetTimeMs() - g_RotateTime) / 1000.0f; float quat[4]; SetQuaternionFromAxisAngle(axis, angle, quat); MultiplyQuaternions(g_RotateStart, quat, g_Rotation); } ConvertQuaternionToMatrix(g_Rotation, mat); glMultMatrixf(mat); glScalef(g_Zoom, g_Zoom, g_Zoom); glCallList(DRAW_EN); glPopMatrix(); GLuint currentProgram = programs[currentShader]; if (currentShader == 1) { glUseProgram(0); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, lightDiffuse); glLightfv(GL_LIGHT0, GL_POSITION, lightPositon); float materialAmbient[] = { rf[0] * 0.2f, rf[1] * 0.2f, rf[2] * 0.2f }; float materialDiffuse[] = { rf[0] * 0.6f, rf[1] * 0.6f, rf[2] * 0.6f }; float materialSpecular[] = { 1 - rf[0] * roughness / 2, 1 - rf[1] * roughness / 2, 1 - rf[2] * roughness / 2 }; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, materialAmbient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, materialDiffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 24); } else { glUseProgram(currentProgram); glUniform1i(glGetUniformLocation(currentProgram, "env_brdf"), IBL); //#####glUniform1i(glGetUniformLocation(currentProgram, "env_map"), MAP); glUniform1i(glGetUniformLocation(currentProgram, "cubemap"), MAP); glUniform1i(glGetUniformLocation(currentProgram, "tex"), TEX); //glUniform1i(glGetUniformLocation(currentShader, "lightNum"), 0); //glUniform1f(glGetUniformLocation(currentProgram, "density"), lightAmbient[1]); //glUniform3fv(glGetUniformLocation(currentProgram, "ambient"), 1, lightAmbient); glLightfv(GL_LIGHT0, GL_POSITION, lightPositon); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse); glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient); //glUniform3fv(glGetUniformLocation(currentProgram, "lightPos"), 1, lightPositon); //glUniform3fv(glGetUniformLocation(currentProgram, "diffuse"), 1, lightDiffuse); glUniform3fv(glGetUniformLocation(currentProgram, "rf"), 1, rf); glUniform1f(glGetUniformLocation(currentProgram, "roughness"), roughness); glUniform1i(glGetUniformLocation(currentProgram, "iftex"), -1); glUniformMatrix4fv(glGetUniformLocation(currentProgram, "g_rotation"), 1, GL_FALSE, mat); } // Rotate and draw shape glPushMatrix(); glTranslatef(0.5f, -0.3f, 0.0f); if (g_AutoRotate) { float axis[3] = { 0, 1, 0 }; float angle = (float)(GetTimeMs() - g_RotateTime) / 1000.0f; float quat[4]; SetQuaternionFromAxisAngle(axis, angle, quat); MultiplyQuaternions(g_RotateStart, quat, g_Rotation); } ConvertQuaternionToMatrix(g_Rotation, mat); glMultMatrixf(mat); glScalef(g_Zoom, g_Zoom, g_Zoom); glCallList(g_CurrentShape); glPopMatrix(); glUseProgram(0); // Draw tweak bars TwDraw(); // Present frame buffer glutSwapBuffers(); // Recall Display at next frame glutPostRedisplay(); }
/** Draws the bars */ void RTweakBar::Draw() { if(IsActive) TwDraw(); }
void Display(void) { //display the background image here /*glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 1, 0, 1, -1, 1); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glDepthMask(GL_FALSE); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRasterPos2i(0, 0); glDrawPixels()*/ /* glClearColor(1.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glEnable(GL_TEXTURE_2D); */ //background(); float v[4]; float v1[4]; float mat[4 * 4]; glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glEnable(GL_NORMALIZE); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); v[0] = v[1] = v[2] = g_LightMultiplier*0.4f; v[3] = 1.0f; glLightfv(GL_LIGHT0, GL_AMBIENT, v); v[0] = v[1] = v[2] = g_LightMultiplier*0.8f; v[3] = 1.0f; glLightfv(GL_LIGHT0, GL_DIFFUSE, v); v[0] = -g_LightDirection[0]; v[1] = -g_LightDirection[1]; v[2] = -g_LightDirection[2]; v[3] = 0.0f; glLightfv(GL_LIGHT0, GL_POSITION, v); glEnable(GL_LIGHTING); glEnable(GL_LIGHT1); v1[0] = v1[1] = v1[2] = g_LightMultiplier*0.4f; v1[3] = 1.0f; glLightfv(GL_LIGHT1, GL_AMBIENT, v1); v1[0] = v1[1] = v1[2] = g_LightMultiplier*0.8f; v1[3] = 1.0f; glLightfv(GL_LIGHT1, GL_DIFFUSE, v1); v1[0] = -g_LightDirection2[0]; v1[1] = -g_LightDirection2[1]; v1[2] = -g_LightDirection2[2]; v1[3] = 0.0f; glLightfv(GL_LIGHT1, GL_POSITION, v1); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, g_MatAmbient1); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, g_MatDiffuse1); glPushMatrix(); glTranslatef(0.5f, -0.3f, 0.0f); if (g_AutoRotate) { float axis[3] = { 0, 1, 0 }; float angle = (float)(GetTimeMs() - g_RotateTime) / 1000.0f; float quat[4]; SetQuaternionFromAxisAngle(axis, angle, quat); MultiplyQuaternions(g_RotateStart, quat, g_Rotation); } ConvertQuaternionToMatrix(g_Rotation, mat); glMultMatrixf(mat); glScalef(g_Zoom, g_Zoom, g_Zoom); Matrices identity; animation->evaluate(newTime); if (animate){ float timeDiff = currentTime - prevTime; prevTime = currentTime; currentTime = time(NULL); newTime = newTime + 0.01; } skeletonWasp->calculate(identity.IDENTITY); skinningWasp->update(); skinningWasp->draw(); glPopMatrix(); TwDraw(); glutSwapBuffers(); glutPostRedisplay(); }
// Display to an HMD with OVR SDK backend. void displayHMD() { ovrSessionStatus sessionStatus; ovr_GetSessionStatus(g_session, &sessionStatus); if (sessionStatus.HmdPresent == false) { displayMonitor(); return; } const ovrHmdDesc& hmdDesc = m_Hmd; double sensorSampleTime; // sensorSampleTime is fed into the layer later if (g_hmdVisible) { // Call ovr_GetRenderDesc each frame to get the ovrEyeRenderDesc, as the returned values (e.g. HmdToEyeOffset) may change at runtime. ovrEyeRenderDesc eyeRenderDesc[2]; eyeRenderDesc[0] = ovr_GetRenderDesc(g_session, ovrEye_Left, hmdDesc.DefaultEyeFov[0]); eyeRenderDesc[1] = ovr_GetRenderDesc(g_session, ovrEye_Right, hmdDesc.DefaultEyeFov[1]); // Get eye poses, feeding in correct IPD offset ovrVector3f HmdToEyeOffset[2] = { eyeRenderDesc[0].HmdToEyeOffset, eyeRenderDesc[1].HmdToEyeOffset }; #if 0 // Get both eye poses simultaneously, with IPD offset already included. double displayMidpointSeconds = ovr_GetPredictedDisplayTime(g_session, 0); ovrTrackingState hmdState = ovr_GetTrackingState(g_session, displayMidpointSeconds, ovrTrue); ovr_CalcEyePoses(hmdState.HeadPose.ThePose, HmdToEyeOffset, m_eyePoses); #else ovr_GetEyePoses(g_session, g_frameIndex, ovrTrue, HmdToEyeOffset, m_eyePoses, &sensorSampleTime); #endif storeHmdPose(m_eyePoses[0]); for (int eye = 0; eye < 2; ++eye) { const FBO& swapfbo = m_swapFBO[eye]; const ovrTextureSwapChain& chain = g_textureSwapChain[eye]; int curIndex; ovr_GetTextureSwapChainCurrentIndex(g_session, chain, &curIndex); GLuint curTexId; ovr_GetTextureSwapChainBufferGL(g_session, chain, curIndex, &curTexId); glBindFramebuffer(GL_FRAMEBUFFER, swapfbo.id); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, curTexId, 0); glViewport(0, 0, swapfbo.w, swapfbo.h); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_FRAMEBUFFER_SRGB); { glClearColor(0.3f, 0.3f, 0.3f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); const ovrSizei& downSize = ovr_GetFovTextureSize(g_session, ovrEyeType(eye), hmdDesc.DefaultEyeFov[eye], m_fboScale); ovrRecti vp = { 0, 0, downSize.w, downSize.h }; const int texh = swapfbo.h; vp.Pos.y = (texh - vp.Size.h) / 2; glViewport(vp.Pos.x, vp.Pos.y, vp.Size.w, vp.Size.h); // Cinemascope - letterbox bars scissoring off pixels above and below vp center const float hc = .5f * m_cinemaScope; const int scisPx = static_cast<int>(hc * static_cast<float>(vp.Size.h)); ovrRecti sp = vp; sp.Pos.y += scisPx; sp.Size.h -= 2 * scisPx; glScissor(sp.Pos.x, sp.Pos.y, sp.Size.w, sp.Size.h); glEnable(GL_SCISSOR_TEST); glEnable(GL_DEPTH_TEST); // Render the scene for the current eye const ovrPosef& eyePose = m_eyePoses[eye]; const glm::mat4 mview = makeWorldToChassisMatrix() * makeMatrixFromPose(eyePose, m_headSize); const ovrMatrix4f ovrproj = ovrMatrix4f_Projection(hmdDesc.DefaultEyeFov[eye], 0.2f, 1000.0f, ovrProjection_None); const glm::mat4 proj = makeGlmMatrixFromOvrMatrix(ovrproj); g_pScene->RenderForOneEye(glm::value_ptr(glm::inverse(mview)), glm::value_ptr(proj)); const ovrTextureSwapChain& chain = g_textureSwapChain[eye]; const ovrResult commitres = ovr_CommitTextureSwapChain(g_session, chain); if (!OVR_SUCCESS(commitres)) { LOG_ERROR("ovr_CommitTextureSwapChain returned %d", commitres); return; } } glDisable(GL_SCISSOR_TEST); // Grab a copy of the left eye's undistorted render output for presentation // to the desktop window instead of the barrel distorted mirror texture. // This blit, while cheap, could cost some framerate to the HMD. // An over-the-shoulder view is another option, at a greater performance cost. if (0) { if (eye == ovrEyeType::ovrEye_Left) { BlitLeftEyeRenderToUndistortedMirrorTexture(); } } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } } std::vector<const ovrLayerHeader*> layerHeaders; { // Do distortion rendering, Present and flush/sync ovrLayerEyeFov ld; ld.Header.Type = ovrLayerType_EyeFov; ld.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; // Because OpenGL. for (int eye = 0; eye < 2; ++eye) { const FBO& swapfbo = m_swapFBO[eye]; const ovrTextureSwapChain& chain = g_textureSwapChain[eye]; ld.ColorTexture[eye] = chain; const ovrSizei& downSize = ovr_GetFovTextureSize(g_session, ovrEyeType(eye), hmdDesc.DefaultEyeFov[eye], m_fboScale); ovrRecti vp = { 0, 0, downSize.w, downSize.h }; const int texh = swapfbo.h; vp.Pos.y = (texh - vp.Size.h) / 2; ld.Viewport[eye] = vp; ld.Fov[eye] = hmdDesc.DefaultEyeFov[eye]; ld.RenderPose[eye] = m_eyePoses[eye]; ld.SensorSampleTime = sensorSampleTime; } layerHeaders.push_back(&ld.Header); // Submit layers to HMD for display ovrLayerQuad ql; if (g_tweakbarQuad.m_showQuadInWorld) { ql.Header.Type = ovrLayerType_Quad; ql.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; // Because OpenGL. ql.ColorTexture = g_tweakbarQuad.m_swapChain; ovrRecti vp; vp.Pos.x = 0; vp.Pos.y = 0; vp.Size.w = 600; ///@todo vp.Size.h = 600; ///@todo ql.Viewport = vp; ql.QuadPoseCenter = g_tweakbarQuad.m_QuadPoseCenter; ql.QuadSize = { 1.f, 1.f }; ///@todo Pass in g_tweakbarQuad.SetHmdEyeRay(m_eyePoses[ovrEyeType::ovrEye_Left]); // Writes to m_layerQuad.QuadPoseCenter g_tweakbarQuad.DrawToQuad(); layerHeaders.push_back(&ql.Header); } } #if 0 ovrViewScaleDesc viewScaleDesc; viewScaleDesc.HmdToEyeOffset[0] = m_eyeOffsets[0]; viewScaleDesc.HmdToEyeOffset[1] = m_eyeOffsets[1]; viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1.f; #endif const ovrResult result = ovr_SubmitFrame(g_session, g_frameIndex, nullptr, &layerHeaders[0], layerHeaders.size()); if (result == ovrSuccess) { g_hmdVisible = true; } else if (result == ovrSuccess_NotVisible) { g_hmdVisible = false; ///@todo Enter a lower-power, polling "no focus/HMD not worn" mode } else if (result == ovrError_DisplayLost) { LOG_INFO("ovr_SubmitFrame returned ovrError_DisplayLost"); g_hmdVisible = false; ///@todo Tear down textures and session and re-create } else { LOG_INFO("ovr_SubmitFrame returned %d", result); //g_hmdVisible = false; } // Handle OVR session events ovr_GetSessionStatus(g_session, &sessionStatus); if (sessionStatus.ShouldQuit) { glfwSetWindowShouldClose(g_pMirrorWindow, 1); } if (sessionStatus.ShouldRecenter) { ovr_RecenterTrackingOrigin(g_session); } // Blit mirror texture to monitor window if (g_hmdVisible) { glViewport(0, 0, g_mirrorWindowSz.x, g_mirrorWindowSz.y); const FBO& srcFBO = m_mirrorFBO; glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFBO.id); glBlitFramebuffer( 0, srcFBO.h, srcFBO.w, 0, 0, 0, g_mirrorWindowSz.x, g_mirrorWindowSz.y, GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); } else { displayMonitor(); } ++g_frameIndex; #ifdef USE_ANTTWEAKBAR if (g_tweakbarQuad.m_showQuadInWorld) { TwDraw(); } #endif }
void RenderFunction(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 ProjectionMatrix; glm::mat4 ViewMatrix; glm::mat4 ModelMatrix = glm::mat4(1.0f); glm::mat4 MVPMatrix; glm::vec3 camPos; GLfloat global_ambient[] = { global_r, global_g, global_b, 1.0f }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); //Perspective GLfloat aspect = (GLfloat)width / (GLfloat)height; glViewport(0, 0, (GLsizei)width, (GLsizei)height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(100.0, aspect, 1.0, 3000.0); ProjectionMatrix = glm::perspective(45.0f, 4.0f/3.0f , 1.0f, 1000.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); if (ori == 0) glFrontFace(GL_CCW); else if (ori == 1) glFrontFace(GL_CW); switch (model) { case 0: gluLookAt(0, 0, 1, 0, 0, -2, 0, 1, 0); ViewMatrix = glm::lookAt(glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -2.0f), glm::vec3(0.0f, 1.0f, 0.0f)); camPos = { 0.0f, 1.0f, 0.0f }; break; case 1: gluLookAt((x_min + x_max) / 2, (y_min + y_max) / 2, 800 + (z_min + z_max) / 2, (x_min + x_max) / 2, (y_min + y_max) / 2, (z_min + z_max) / 2, 0, 1, 0); ViewMatrix = glm::lookAt(glm::vec3( (x_min + x_max) / 2, (y_min + y_max) / 2, 800 + (z_min + z_max) / 2 ), glm::vec3( (x_min + x_max) / 2, (y_min + y_max) / 2, (z_min + z_max) / 2 ), glm::vec3( 0.0f, 1.0f, 0.0f )); camPos = { (x_min + x_max) / 2, (y_min + y_max) / 2, 800 + (z_min + z_max) / 2 }; break; case 2: gluLookAt((x_min + x_max) / 2, (y_min + y_max) / 2 - 30, 400 + (z_min + z_max) / 2, (x_min + x_max) / 2, (y_min + y_max) / 2, (z_min + z_max) / 2, 0, 1, 0); glTranslatef(80, 100, 0); ViewMatrix = glm::lookAt(glm::vec3( (x_min + x_max) / 2 + 80, (y_min + y_max) / 2 + 70, 400 + (z_min + z_max) / 2 ), glm::vec3( (x_min + x_max) / 2 + 80, (y_min + y_max) / 2 + 100, (z_min + z_max) / 2 ), glm::vec3( 0.0f, 1.0f, 0.0f )); camPos = { (x_min + x_max) / 2 + 80, (y_min + y_max) / 2 + 70, 400 + (z_min + z_max) / 2 }; break; } MVPMatrix = ProjectionMatrix * ViewMatrix * ModelMatrix; SetUniform(programID, camPos, ModelMatrix, ViewMatrix, MVPMatrix, sLight, dLight); glDrawArrays(GL_TRIANGLES, 0, NumTris); TwDraw(); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glPopMatrix(); glutSwapBuffers(); }
// Main int main() { // Create main window sf::RenderWindow app(sf::VideoMode(800, 600), "AntTweakBar simple example using SFML"); app.PreserveOpenGLStates(true); // Particules std::list<Particle> particles; std::list<Particle>::iterator p; float birthCount = 0; float birthRate = 20; // number of particles generated per second float maxAge = 3.0f; // particles life time float speedDir[3] = {0, 1, 0}; // initial particles speed direction float speedNorm = 7.0f; // initial particles speed amplitude float size = 0.1f; // particles size float color[3] = {0.8f, 0.6f, 0}; // particles color float bgColor[3] = {0, 0.6f, 0.6f}; // background color // Initialize AntTweakBar TwInit(TW_OPENGL, NULL); // Tell the window size to AntTweakBar TwWindowSize(app.GetWidth(), app.GetHeight()); // Create a tweak bar TwBar *bar = TwNewBar("Particles"); TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with SFML and OpenGL.' "); // Message added to the help bar. // Change bar position int barPos[2] = {16, 240}; TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, &barPos); // Add 'birthRate' to 'bar': this is a modifiable variable of type TW_TYPE_FLOAT in range [0.1, 100]. Its shortcuts are [+] and [-]. TwAddVarRW(bar, "Birth rate", TW_TYPE_FLOAT, &birthRate, " min=0.1 max=100 step=0.1 keyIncr='+' keyDecr='-' "); // Add 'speedNorm' to 'bar': this is a modifiable variable of type TW_TYPE_FLOAT in range [0.1, 10]. Its shortcuts are [s] and [S]. TwAddVarRW(bar, "Speed", TW_TYPE_FLOAT, &speedNorm, " min=0.1 max=10 step=0.1 keyIncr='s' keyDecr='S' "); // Add 'speedDir' to 'bar': this is a modifiable variable of type TW_TYPE_DIR3F. Just displaying the arrow widget TwAddVarRW(bar, "Direction", TW_TYPE_DIR3F, &speedDir, " opened=true showval=false "); // Add 'color' to 'bar': this is a modifiable variable of type TW_TYPE_COLOR3F. Switched to HLS TwAddVarRW(bar, "Color", TW_TYPE_COLOR3F, &color, " colorMode=hls opened=true "); // Add 'bgColor' to 'bar': this is a modifiable variable of type TW_TYPE_COLOR3F. Switched to HLS TwAddVarRW(bar, "Background color", TW_TYPE_COLOR3F, &bgColor, " colorMode=hls opened=true "); // Initialize OpenGL states glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, (float)app.GetWidth()/app.GetHeight(), 0.1f, 100.f); glMatrixMode(GL_MODELVIEW); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); // Init time sf::Clock clock; float time = clock.GetElapsedTime(); // Main loop while (app.IsOpened()) { // Process events sf::Event event; while (app.GetEvent(event)) { // Send event to AntTweakBar int handled = TwEventSFML(&event, 1, 6); // Assume SFML version 1.6 here // If event has not been handled by AntTweakBar, process it if( !handled ) { // Close or Escape if (event.Type == sf::Event::Closed || (event.Type == sf::Event::KeyPressed && event.Key.Code == sf::Key::Escape)) app.Close(); // Resize if (event.Type == sf::Event::Resized) { glViewport(0, 0, event.Size.Width, event.Size.Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, (float)event.Size.Width/event.Size.Height, 1.f, 500.f); glMatrixMode(GL_MODELVIEW); // TwWindowSize has been called by TwEventSFML, // so it is not necessary to call it again here. } } } if (!app.IsOpened()) continue; // Update time float dt = clock.GetElapsedTime() - time; time += dt; // Update particles p = particles.begin(); while (p != particles.end()) { p->Update(dt); if (p->Age >= maxAge) p = particles.erase(p); // Die! else ++p; } // Generate new particles birthCount += dt * birthRate; while (birthCount >= 1.0f) { particles.push_back(Particle(size, speedDir, speedNorm, color)); birthCount--; } // Clear depth buffer glClearColor(bgColor[0], bgColor[1], bgColor[2], 1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Draw particles for (p = particles.begin(); p != particles.end(); ++p) { glColor4fv(p->Color); glLoadIdentity(); glTranslatef(0.0f, -1.0f, -3.0f); // Camera position glTranslatef(p->Position[0], p->Position[1], p->Position[2]); glScalef(p->Size, p->Size, p->Size); glRotatef(p->RotationAngle, p->RotationAxis[0], p->RotationAxis[1], p->RotationAxis[2]); // Draw a cube glBegin(GL_QUADS); glNormal3f(0,0,-1); glVertex3f(0,0,0); glVertex3f(0,1,0); glVertex3f(1,1,0); glVertex3f(1,0,0); // front face glNormal3f(0,0,+1); glVertex3f(0,0,1); glVertex3f(1,0,1); glVertex3f(1,1,1); glVertex3f(0,1,1); // back face glNormal3f(-1,0,0); glVertex3f(0,0,0); glVertex3f(0,0,1); glVertex3f(0,1,1); glVertex3f(0,1,0); // left face glNormal3f(+1,0,0); glVertex3f(1,0,0); glVertex3f(1,1,0); glVertex3f(1,1,1); glVertex3f(1,0,1); // right face glNormal3f(0,-1,0); glVertex3f(0,0,0); glVertex3f(1,0,0); glVertex3f(1,0,1); glVertex3f(0,0,1); // bottom face glNormal3f(0,+1,0); glVertex3f(0,1,0); glVertex3f(0,1,1); glVertex3f(1,1,1); glVertex3f(1,1,0); // top face glEnd(); } TwDraw(); // Finally, display the rendered frame on screen app.Display(); } // Un-initialize AntTweakBar TwTerminate(); return EXIT_SUCCESS; }
void Render() { if (!g_CanDraw) return; auto width = glutGet(GLUT_WINDOW_WIDTH); auto height = glutGet(GLUT_WINDOW_HEIGHT); glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // variables uniformes (constantes) g_Camera.projectionMatrix = glm::perspectiveFov(45.f, (float)width, (float)height, 0.1f, 1000.f); // rotation orbitale de la camera float rotY = glm::radians(g_Camera.rotation.y); const glm::vec4 orbitDistance(0.0f, 0.0f, 200.0f, 1.0f); glm::vec4 position = /*glm::eulerAngleY(rotY) **/ orbitDistance; g_Camera.viewMatrix = glm::lookAt(glm::vec3(position), glm::vec3(0.f), glm::vec3(0.f, 1.f, 0.f)); glBindBuffer(GL_UNIFORM_BUFFER, g_Camera.UBO); //glBufferData(GL_UNIFORM_BUFFER, sizeof(glm::mat4) * 2, glm::value_ptr(g_Camera.viewMatrix), GL_STREAM_DRAW); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4) * 2, glm::value_ptr(g_Camera.viewMatrix)); for (uint32_t index = 0; index < g_Spheres.size(); ++index) { static const float radius = 100.0f; // L'illumination s'effectue dans le repere de la camera, il faut donc que les positions des lumieres // soient egalement exprimees dans le meme repere (view space) g_PointLights[index].position = g_Camera.viewMatrix * glm::vec4(g_Spheres[index].position, 1.0f); g_PointLights[index].position.w = radius; } glBindBuffer(GL_UNIFORM_BUFFER, PointLight::UBO); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(PointLight) * g_NumPointLights, g_PointLights); // rendu des murs avec illumination glBindVertexArray(g_WallMesh.VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); auto program = g_BlinnPhongShader.GetProgram(); glUseProgram(program); auto numLightsLocation = glGetUniformLocation(program, "u_numLights"); glUniform1i(numLightsLocation, g_NumPointLights); auto worldLocation = glGetUniformLocation(program, "u_worldMatrix"); glm::mat4& transform = g_Walls.worldMatrix; glUniformMatrix4fv(worldLocation, 1, GL_FALSE, glm::value_ptr(transform)); auto startIndex = 0; glBindTexture(GL_TEXTURE_2D, g_Walls.textures[Walls::gWallTexture]); glDrawArrays(GL_TRIANGLES, startIndex, 6 * 4); startIndex += 6 * 4; // 4 murs glBindTexture(GL_TEXTURE_2D, g_Walls.textures[Walls::gCeilingTexture]); glDrawArrays(GL_TRIANGLES, startIndex, 6); startIndex += 6; // plafond glBindTexture(GL_TEXTURE_2D, g_Walls.textures[Walls::gFloorTexture]); glDrawArrays(GL_TRIANGLES, startIndex, 6); startIndex += 6; // sol // rendu debug glBindTexture(GL_TEXTURE_2D, 0); glBindVertexArray(g_SphereMesh.VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_SphereMesh.IBO); program = g_AmbientShader.GetProgram(); glUseProgram(program); worldLocation = glGetUniformLocation(program, "u_worldMatrix"); for (auto index = 0; index < g_Spheres.size(); ++index) { glm::mat4& transform = g_Spheres[index].worldMatrix; glUniformMatrix4fv(worldLocation, 1, GL_FALSE, glm::value_ptr(transform)); glDrawElements(GL_TRIANGLES, g_SphereMesh.ElementCount, GL_UNSIGNED_INT, 0); } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //glBindVertexArray(0); // dessine les tweakBar TwDraw(); glutSwapBuffers(); }
void ofxTweakbars::draw() { if(instance.visible) TwDraw(); }
// Main function int main() { // Initialize GLFW if( !glfwInit() ) { // A fatal error occurred std::cerr << "GLFW initialization failed" << std::endl; return 1; } // Create a window GLFWvidmode mode; glfwGetDesktopMode(&mode); if( !glfwOpenWindow(800, 600, mode.RedBits, mode.GreenBits, mode.BlueBits, 0, 16, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) ) { // A fatal error occurred std::cerr << "Cannot open GLFW window" << std::endl; glfwTerminate(); return 1; } glfwSwapInterval(0); glfwEnable(GLFW_MOUSE_CURSOR); glfwEnable(GLFW_KEY_REPEAT); const char title[] = "AntTweakBar example: TwAdvanced1"; glfwSetWindowTitle(title); // Set GLFW event callbacks glfwSetWindowSizeCallback(OnWindowSize); glfwSetMouseButtonCallback(OnMouseButton); glfwSetMousePosCallback(OnMousePos); glfwSetMouseWheelCallback(OnMouseWheel); glfwSetKeyCallback(OnKey); glfwSetCharCallback(OnChar); // Initialize AntTweakBar TwInit(TW_OPENGL, NULL); // Change the font size, and add a global message to the Help bar. TwDefine(" GLOBAL fontSize=3 help='This example illustrates the definition of custom structure type as well as many other features.' "); // Initialize the 3D scene Scene scene; scene.Init(true); // Create a tweak bar called 'Main' and change its refresh rate, position, size and transparency TwBar *mainBar = TwNewBar("Main"); TwDefine(" Main label='Main TweakBar' refresh=0.5 position='16 16' size='260 320' alpha=0"); // Add some variables to the Main tweak bar TwAddVarRW(mainBar, "Wireframe", TW_TYPE_BOOLCPP, &scene.Wireframe, " group='Display' key=w help='Toggle wireframe display mode.' "); // 'Wireframe' is put in the group 'Display' (which is then created) TwAddVarRW(mainBar, "BgTop", TW_TYPE_COLOR3F, &scene.BgColor1, " group='Background' help='Change the top background color.' "); // 'BgTop' and 'BgBottom' are put in the group 'Background' (which is then created) TwAddVarRW(mainBar, "BgBottom", TW_TYPE_COLOR3F, &scene.BgColor0, " group='Background' help='Change the bottom background color.' "); TwDefine(" Main/Background group='Display' "); // The group 'Background' of bar 'Main' is put in the group 'Display' TwAddVarCB(mainBar, "Subdiv", TW_TYPE_INT32, SetSubdivCB, GetSubdivCB, &scene, " group='Scene' label='Meshes subdivision' min=1 max=50 keyincr=s keyDecr=S help='Subdivide the meshes more or less (switch to wireframe to see the effect).' "); TwAddVarRW(mainBar, "Ambient", TW_TYPE_FLOAT, &scene.Ambient, " label='Ambient factor' group='Scene' min=0 max=1 step=0.001 keyIncr=a keyDecr=A help='Change scene ambient.' "); TwAddVarRW(mainBar, "Reflection", TW_TYPE_FLOAT, &scene.Reflection, " label='Reflection factor' group='Scene' min=0 max=1 step=0.001 keyIncr=r keyDecr=R help='Change ground reflection.' "); // Create a new TwType called rotationType associated with the Scene::RotMode enum, and use it TwEnumVal rotationEV[] = { { Scene::ROT_OFF, "Stopped"}, { Scene::ROT_CW, "Clockwise" }, { Scene::ROT_CCW, "Counter-clockwise" } }; TwType rotationType = TwDefineEnum( "Rotation Mode", rotationEV, 3 ); TwAddVarRW(mainBar, "Rotation", rotationType, &scene.Rotation, " group='Scene' keyIncr=Backspace keyDecr=SHIFT+Backspace help='Stop or change the rotation mode.' "); // Add a read-only float variable; its precision is 0 which means that the fractionnal part of the float value will not be displayed TwAddVarRO(mainBar, "RotYAngle", TW_TYPE_DOUBLE, &scene.RotYAngle, " group='Scene' label='Rot angle (degree)' precision=0 help='Animated rotation angle' "); // Initialize time double time = glfwGetTime(), dt = 0; // Current time and elapsed time double frameDTime = 0, frameCount = 0, fps = 0; // Framerate // Main loop (repeated while window is not closed) while( glfwGetWindowParam(GLFW_OPENED) ) { // Get elapsed time dt = glfwGetTime() - time; if (dt < 0) dt = 0; time += dt; // Rotate scene if( scene.Rotation==Scene::ROT_CW ) scene.RotYAngle -= 5.0*dt; else if( scene.Rotation==Scene::ROT_CCW ) scene.RotYAngle += 5.0*dt; // Move lights scene.Update(time); // Draw scene scene.Draw(); // Draw tweak bars TwDraw(); // Present frame buffer glfwSwapBuffers(); // Estimate framerate frameCount++; frameDTime += dt; if( frameDTime>1.0 ) { fps = frameCount/frameDTime; char newTitle[128]; _snprintf(newTitle, sizeof(newTitle), "%s (%.1f fps)", title, fps); //glfwSetWindowTitle(newTitle); // uncomment to display framerate frameCount = frameDTime = 0; } } // Terminate AntTweakBar and GLFW TwTerminate(); glfwTerminate(); return 0; }
int main() { const SDL_VideoInfo* video = NULL; int width = 480, height = 480; int bpp, flags; int quit = 0; // Initialize SDL, then get the current video mode and use it to create a SDL window. if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Video initialization failed: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } video = SDL_GetVideoInfo(); if (!video) { fprintf(stderr, "Video query failed: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } // Request GL context to be OpenGL 3.2 Core Profile SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); // Other GL attributes SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); bpp = video->vfmt->BitsPerPixel; flags = SDL_OPENGL | SDL_HWSURFACE; if (!SDL_SetVideoMode(width, height, bpp, flags)) { fprintf(stderr, "Video mode set failed: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } SDL_WM_SetCaption("AntTweakBar example using OpenGL Core Profile and SDL", "AntTweakBar+GLCore+SDL"); // Enable SDL unicode and key-repeat SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); // Load some OpenGL core functions if (!LoadGLCoreFunctions()) { fprintf(stderr, "OpenGL 3.2 not supported.\n"); SDL_Quit(); exit(1); } // Initialize AntTweakBar if (!TwInit(TW_OPENGL_CORE, NULL)) { fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError()); SDL_Quit(); exit(1); } // Tell the window size to AntTweakBar TwWindowSize(width, height); // Create a tweak bar CreateTweakBar(); // Set OpenGL viewport glViewport(0, 0, width, height); // Prepare GL shaders and programs for drawing InitRender(); // Main loop: // - Draw scene // - Process events while (!quit) { SDL_Event event; int handled; GLenum error; // Clear screen glClearColor(0.5f, 0.75f, 0.8f, 1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Update angle and draw geometry angle = (float)SDL_GetTicks()/25.0f * (FLOAT_PI/180.0f); quat[0] = quat[1] = 0; quat[2] = (float)sin(angle/2.0f); quat[3] = (float)cos(angle/2.0f); Render(); // Draw tweak bars TwDraw(); // Present frame buffer SDL_GL_SwapBuffers(); // Process incoming events while (SDL_PollEvent(&event)) { // Send event to AntTweakBar handled = TwEventSDL(&event, SDL_MAJOR_VERSION, SDL_MINOR_VERSION); // If event has not been handled by AntTweakBar, process it if (!handled) { switch (event.type) { case SDL_QUIT: // Window is closed quit = 1; break; case SDL_VIDEORESIZE: // Window size has changed // Resize SDL video mode width = event.resize.w; height = event.resize.h; if (!SDL_SetVideoMode(width, height, bpp, flags)) fprintf(stderr, "WARNING: Video mode set failed: %s\n", SDL_GetError()); // Resize OpenGL viewport glViewport(0, 0, width, height); // Restore OpenGL states InitRender(); // TwWindowSize has been called by TwEventSDL, // so it is not necessary to call it again here. break; } } } while ((error = glGetError()) != GL_NO_ERROR) fprintf(stderr, "GL error detected: 0x%04X\n", error); } // End of main loop // Terminate AntTweakBar TwTerminate(); // Delete GL shaders and buffer UninitRender(); // Terminate SDL SDL_Quit(); return 0; }
void TessGui::v_render() { TwDraw(); }
// Main int WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, int cmdShow) { // Register our window class WNDCLASSEX wcex = { sizeof(WNDCLASSEX), CS_CLASSDC|CS_DBLCLKS, MessageProc, 0L, 0L, instance, NULL, NULL, NULL, NULL, "TwDX9", NULL }; RegisterClassEx(&wcex); // Create a window const int W = 640; const int H = 480; BOOL fullscreen = FALSE; // Set to TRUE to run in fullscreen RECT rect = { 0, 0, W, H }; DWORD style = fullscreen ? WS_POPUP : WS_OVERLAPPEDWINDOW; AdjustWindowRect(&rect, style, FALSE); HWND wnd = CreateWindow("TwDX9", "AntTweakBar simple example using DirectX9", style, CW_USEDEFAULT, CW_USEDEFAULT, rect.right-rect.left, rect.bottom-rect.top, NULL, NULL, instance, NULL); if( !wnd ) { MessageBox(NULL, "Cannot create window", "Error", MB_OK|MB_ICONERROR); return FALSE; } ShowWindow(wnd, cmdShow); UpdateWindow(wnd); // Initialize Direct3D g_D3D = Direct3DCreate9(D3D_SDK_VERSION); if( !g_D3D ) { MessageBox(wnd, "Cannot initialize DirectX", "Error", MB_OK|MB_ICONERROR); return FALSE; } // Create a Direct3D device ZeroMemory( &g_D3Dpp, sizeof(D3DPRESENT_PARAMETERS) ); g_D3Dpp.Windowed = !fullscreen; if( fullscreen ) { g_D3Dpp.BackBufferWidth = W; g_D3Dpp.BackBufferHeight = H; } g_D3Dpp.BackBufferCount = 1; g_D3Dpp.SwapEffect = D3DSWAPEFFECT_FLIP; if( fullscreen ) g_D3Dpp.BackBufferFormat = D3DFMT_X8R8G8B8; else g_D3Dpp.BackBufferFormat = D3DFMT_UNKNOWN; g_D3Dpp.hDeviceWindow = wnd; g_D3Dpp.EnableAutoDepthStencil = TRUE; g_D3Dpp.AutoDepthStencilFormat = D3DFMT_D16; g_D3Dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; HRESULT hr = g_D3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, wnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &g_D3Dpp, &g_D3DDev); if( FAILED(hr) ) { //DXTRACE_ERR_MSGBOX("Cannot create DirectX device", hr); MessageBox(wnd, "Cannot create DirectX device", "Error", MB_OK|MB_ICONERROR); g_D3D->Release(); g_D3D = NULL; return FALSE; } // This example draws a moving strip; // create a buffer of vertices for the strip struct Vertex { float x, y, z; DWORD color; }; Vertex vertices[2002]; int numSec = 100; // number of strip sections float color[] = { 1, 0, 0 }; // strip color unsigned int bgColor = D3DCOLOR_ARGB(255, 128, 196, 196); // background color // Init some D3D states InitD3D(); // Initialize AntTweakBar // (note that the Direct3D device pointer must be passed to TwInit) if( !TwInit(TW_DIRECT3D9, g_D3DDev) ) { MessageBox(wnd, TwGetLastError(), "Cannot initialize AntTweakBar", MB_OK|MB_ICONERROR); g_D3DDev->Release(); g_D3DDev = NULL; g_D3D->Release(); g_D3D = NULL; return FALSE; } // Create a tweak bar TwBar *bar = TwNewBar("TweakBar"); TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar in a DirectX9 application.' "); // Message added to the help bar. TwDefine(" TweakBar color='128 224 160' text=dark "); // Change TweakBar color and use dark text // Add 'numSec' to 'bar': it is a modifiable (RW) variable of type TW_TYPE_INT32. Its shortcuts are [s] and [S]. TwAddVarRW(bar, "NumSec", TW_TYPE_INT32, &numSec, " label='Strip length' min=1 max=1000 keyIncr=s keyDecr=S help='Number of segments of the strip.' "); // Add 'color' to 'bar': it is a modifiable variable of type TW_TYPE_COLOR3F (3 floats color) TwAddVarRW(bar, "Color", TW_TYPE_COLOR3F, &color, " label='Strip color' "); // Add 'bgColor' to 'bar': it is a modifiable variable of type TW_TYPE_COLOR32 (32 bits color) TwAddVarRW(bar, "BgColor", TW_TYPE_COLOR32, &bgColor, " label='Background color' "); // Add 'width' and 'height' to 'bar': they are read-only (RO) variables of type TW_TYPE_INT32. TwAddVarRO(bar, "Width", TW_TYPE_INT32, &g_D3Dpp.BackBufferWidth, " label='wnd width' help='Current graphics window width.' "); TwAddVarRO(bar, "Height", TW_TYPE_INT32, &g_D3Dpp.BackBufferHeight, " label='wnd height' help='Current graphics window height.' "); // Main loop bool quit = false; while( !quit ) { // Clear screen and begin draw g_D3DDev->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, bgColor, 1.0f, 0); g_D3DDev->BeginScene(); // Draw scene float s, t = (float)GetTickCount()/1000.0f; for( int i=0; i<=numSec; ++i ) // update vertices { s = (float)i/100; vertices[2*i+0].x = 0.05f+0.7f*cosf(2.0f*s+5.0f*t); vertices[2*i+1].x = vertices[2*i+0].x + (0.25f+0.1f*cosf(s+t)); vertices[2*i+0].y = vertices[2*i+1].y = 0.7f*(0.7f+0.3f*sinf(s+t))*sinf(1.5f*s+3.0f*t); vertices[2*i+0].z = vertices[2*i+1].z = 0; s = (float)i/numSec; vertices[2*i+0].color = vertices[2*i+1].color = D3DCOLOR_XRGB((int)(255*color[0]*s), (int)(255*color[1]*s), (int)(255*color[2]*s)); } g_D3DDev->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE); g_D3DDev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2*numSec, vertices, sizeof(Vertex)); // draw strip // Draw tweak bars TwDraw(); // End draw g_D3DDev->EndScene(); // Present frame buffer g_D3DDev->Present(NULL, NULL, NULL, NULL); // Process windows messages MSG msg; while( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) ) { if( msg.message==WM_QUIT ) quit = true; else if( !TranslateAccelerator(msg.hwnd, NULL, &msg) ) { TranslateMessage(&msg); DispatchMessage(&msg); } } } // End of main loop // Terminate AntTweakBar TwTerminate(); // Release Direct3D g_D3DDev->Release(); g_D3DDev = NULL; g_D3D->Release(); g_D3D = NULL; return 0; }
void Display () { glClearColor ( 80.0f/255.0f, 209.0f/255.0f, 235.0f/255.0f, 1.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); float MaxScale = lightmesh->getMaxScale(); glm::vec3 vecScale = glm::vec3 ( 0.2f/MaxScale, 0.2f/MaxScale, 0.2f/MaxScale ); glm::vec3 tras = glm::vec3(g_light->position.x,g_light->position.y,g_light->position.z); glm::vec3 Center = lightmesh->getCenter(); ModelMatrix = glm :: translate ( glm::mat4 (1.0f), Center ); ModelMatrix = glm :: scale ( ModelMatrix, vecScale ); ModelMatrix = glm :: translate ( ModelMatrix, tras ); ModelView = ViewMatrix * ModelMatrix; NormalMatrix = glm::transpose( glm::inverse (ModelView) ); LightShader->Habilitar(); LightShader->CargarMatrizUniforme( "ModelView", glm::value_ptr(ModelView) ); LightShader->CargarMatrizUniforme( "Projection", glm::value_ptr(ProjectionMatrix)); LightShader->CargarMatrizUniforme( "NormalMatrix", glm::value_ptr(NormalMatrix)); LightShader->CargarUniforme(LightShader->LocacionUniforme("Color"), 3, glm::value_ptr(g_light->ambient)); lightmesh->OpenGLDrawShader(); lightmesh->DrawBoundingBox(); for (int i = 0; i < 4; i++) { MaxScale = lightmesh->getMaxScale(); vecScale = glm::vec3 ( 0.2f/MaxScale, 0.2f/MaxScale, 0.2f/MaxScale ); tras = glm::vec3(lights[i]->position.x,lights[i]->position.y,lights[i]->position.z); Center = lightmesh->getCenter(); ModelMatrix = glm :: translate ( glm::mat4 (1.0f), Center ); ModelMatrix = glm :: scale ( ModelMatrix, vecScale ); ModelMatrix = glm :: translate ( ModelMatrix, tras ); ModelView = ViewMatrix * ModelMatrix; NormalMatrix = glm::transpose( glm::inverse (ModelView) ); LightShader->CargarMatrizUniforme( "ModelView", glm::value_ptr(ModelView) ); LightShader->CargarMatrizUniforme( "Projection", glm::value_ptr(ProjectionMatrix)); LightShader->CargarMatrizUniforme( "NormalMatrix", glm::value_ptr(NormalMatrix)); LightShader->CargarUniforme(LightShader->LocacionUniforme("Color"), 3, glm::value_ptr(g_light->ambient)); lightmesh->OpenGLDrawShader(); } LightShader->Deshabilitar(); if(actualModel!=NULL){ float MaxScale = actualModel->getMaxScale(); glm::vec3 vecScale = glm::vec3 ( g_Zoom/MaxScale, g_Zoom/MaxScale, g_Zoom/MaxScale ); glm::vec3 tras = glm::vec3(Translation[0],Translation[1],Translation[2]); glm::vec3 Center = actualModel->getCenter(); glm::mat4 rot = glm::mat4_cast(g_Rotation); //rot = glm::transpose(rot); ModelMatrix = glm :: translate ( glm::mat4 (1.0f), Center ); ModelMatrix = rot * ModelMatrix; ModelMatrix = glm :: scale ( ModelMatrix, vecScale ); ModelMatrix = glm :: translate ( ModelMatrix, tras ); ModelView = ViewMatrix * ModelMatrix; glm::mat4 MVP = ProjectionMatrix * ModelView; NormalMatrix = glm::transpose( glm::inverse (ModelView) ); ProgramShader->Habilitar(); ProgramShader->CargarMatrizUniforme( "ModelView", glm::value_ptr(ModelView) ); ProgramShader->CargarMatrizUniforme( "Projection", glm::value_ptr(ProjectionMatrix)); ProgramShader->CargarMatrizUniforme( "NormalMatrix", glm::value_ptr(NormalMatrix)); ProgramShader->CargarUniforme( ProgramShader->LocacionUniforme("shinnes"), 1, &shinnes ); /* ProgramShader->CargarUniforme(ProgramShader->LocacionUniforme("lightposition"), 4, glm::value_ptr(ligthposition)); ProgramShader->CargarUniforme(ProgramShader->LocacionUniforme("Kd"), 3, glm::value_ptr(Kd)); ProgramShader->CargarUniforme(ProgramShader->LocacionUniforme("Ld"), 3, glm::value_ptr(Ld)); ProgramShader->CargarUniforme( ProgramShader->LocacionUniforme("Color"), 3, Color );*/ actualModel->OpenGLDrawShader(); actualModel->DrawBoundingBox(); ProgramShader->Deshabilitar(); } if ( !Model.empty() ) { for(int i = 0; i<(int)Model.size(); i++){ float MaxScale = Model[i]->getMaxScale(); glm::vec3 vecScale = glm::vec3 ( zoom[i]/MaxScale, zoom[i]/MaxScale, zoom[i]/MaxScale ); glm::vec3 tras = glm::vec3(translate[i][0],translate[i][1],translate[i][2]); glm::vec3 Center = Model[i]->getCenter(); /*Center.x = -Center.x; Center.y = -Center.y; Center.z = -Center.z; */ glm::mat4 rot = glm::mat4_cast(rotation[i]); rot = glm::transpose(rot); ModelMatrix = glm :: translate ( glm::mat4 (1.0f), Center ); ModelMatrix = rot * ModelMatrix; ModelMatrix = glm :: scale ( ModelMatrix, vecScale ); ModelMatrix = glm :: translate ( ModelMatrix, tras ); ModelView = ViewMatrix * ModelMatrix; glm::mat4 MVP = ProjectionMatrix * ModelView; NormalMatrix = glm::transpose( glm::inverse (ModelView) ); ProgramShader->Habilitar(); ProgramShader->CargarMatrizUniforme( "ModelView", glm::value_ptr(ModelView) ); ProgramShader->CargarMatrizUniforme( "Projection", glm::value_ptr(ProjectionMatrix)); ProgramShader->CargarMatrizUniforme( "MVP", glm::value_ptr(MVP)); ProgramShader->CargarMatrizUniforme( "NormalMatrix", glm::value_ptr(NormalMatrix)); /* ProgramShader->CargarUniforme(ProgramShader->LocacionUniforme("lightposition"), 4, glm::value_ptr(ligthposition)); ProgramShader->CargarUniforme(ProgramShader->LocacionUniforme("Kd"), 3, glm::value_ptr(Kd)); ProgramShader->CargarUniforme(ProgramShader->LocacionUniforme("Ld"), 3, glm::value_ptr(Ld)); ProgramShader->CargarUniforme( ProgramShader->LocacionUniforme("Color"), 3, Color );*/ Model[i]->OpenGLDrawShader(); ProgramShader->Deshabilitar(); } } // Draw tweak bars TwDraw(); glutSwapBuffers(); // Recall Display at next frame glutPostRedisplay(); }
void Graphics::Render() { mat_stack_->Push(camera_->GetViewMatrix()); scene_constants_.fogNear = std::max(scene_constants_.fogNear, 0.5f); scene_constants_.fogFar = std::max(scene_constants_.fogFar, scene_constants_.fogNear + 1.0f); Matrix4 modelToWorld; BeginScene(); graphicsAPI->SetBlendType(BlendType::Off); graphicsAPI->SetDepthType(DepthType::Normal); //7 passes because reflection is great graphicsAPI->ClearRenderTargets(); graphicsAPI->FlushDepth(); graphicsAPI->ClearShaderResources(); graphicsAPI->AddRenderTarget(back_buffer_); graphicsAPI->SetRenderTargets(); LightingShaderParam paramList; int count = 0; Shader* debugShader = nullptr; for(auto& shaderIt : shaders_) { Shader* shader = shaderIt.val; if(shaderIt.key != "lines" && shaderIt.key != "particle") { Model* model = nullptr; for(auto& modelIt : shader->GetInstances()) { model = modelIt.first; model->Render(); for(auto& inst : modelIt.second) { paramList.modelComp = inst; paramList.shader = shader; shader->PrepareBuffers((void*) ¶mList); shader->Render(model->GetNumVerts()); } } } else { debugShader = shader; } } const bool drawParticles = true; if(drawParticles) { //PARTICLES auto& particleSystems = particle_manager_->GetSystems(); auto shaderIt = shaders_.find("particle"); Shader* particleShader = nullptr; if(shaderIt != shaders_.end()) { particleShader = (*shaderIt).val; } graphicsAPI->SetBlendType(BlendType::Additive); graphicsAPI->SetDepthType(DepthType::Off); ParticleShaderParam particleParam; particleParam.shader = particleShader; Model* particleModel; for(auto& it : particleSystems) { for(auto& particleEmitter : it->GetEmitters()) { particleModel = GetModel(particleEmitter->GetDescription().sourceModel); if(particleModel) { particleModel->Render(); particleParam.emitter = particleEmitter; auto& particles = particleEmitter->GetParticles(); for(auto& particleIndex : particleEmitter->GetAlive()) { particleParam.particle = &particles[particleIndex]; particleShader->PrepareBuffers(&particleParam); particleShader->Render(particleModel->GetNumVerts()); } } } } graphicsAPI->SetBlendType(BlendType::Off); graphicsAPI->SetDepthType(DepthType::Normal); } //if(debugShader) //{ // for(auto& it : debug_models_) // { // if(it->GetDrawType() != DrawType::Default) // { // PrepareDebug(it); // RenderDebug(); // debugShader->PrepareBuffers(it); // debugShader->Render(debug_lines_.size()); // } // } //} if(draw_ui_) { TwDraw(); } EndScene(); mat_stack_->Pop(); }
void drawOverlay() { TwDraw(); }
int main(int argc, const char* argv[]) { const char *me; me = argv[0]; // NOTE: we now allow you to either pass in an "invoked" or default shader to render, or to let // us just set up our stack; hence you either pass 2 additional arguments or none at all // NOTE: we aren't explicity defining this functionality, but obviously `proj2 -h' will show the // usage pattern if (1!=argc && 3!=argc) { usage(me); exit(1); } if (!(gctx = contextNew(10, 10))) { fprintf(stderr, "%s: context set-up problem:\n", me); spotErrorPrint(); spotErrorClear(); exit(1); } if (argc==3) { gctx->vertFname = argv[1]; gctx->fragFname = argv[2]; } else { // NOTE: if invoked with no shaders, set these to NULL; `contextGlInit()' will catch these gctx->vertFname = NULL; gctx->fragFname = NULL; } if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); exit(1); } /* Make sure we're using OpenGL 3.2 core. NOTE: Changing away from OpenGL 3.2 core is not needed and not allowed for this project */ glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); if (!glfwOpenWindow(gctx->winSizeX, gctx->winSizeY, 0, 0, 0, 0, 32, 0, GLFW_WINDOW)) { fprintf(stderr, "Failed to open GLFW window\n"); glfwTerminate(); exit(1); } glfwSetWindowTitle("Project 2: Shady"); glfwEnable(GLFW_MOUSE_CURSOR); glfwEnable(GLFW_KEY_REPEAT); glfwSwapInterval(1); /* Initialize AntTweakBar */ if (!TwInit(TW_OPENGL_CORE, NULL)) { fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError()); exit(1); } printf("GL_RENDERER = %s\n", (char *) glGetString(GL_RENDERER)); printf("GL_VERSION = %s\n", (char *) glGetString(GL_VERSION)); printf("GL_VENDOR = %s\n", (char *) glGetString(GL_VENDOR)); printf("PNG_LIBPNG_VER_STRING = %s\n", PNG_LIBPNG_VER_STRING); /* set-up and initialize the global context */ if (contextGLInit(gctx)) { fprintf(stderr, "%s: context OpenGL set-up problem:\n", me); spotErrorPrint(); spotErrorClear(); TwTerminate(); glfwTerminate(); exit(1); } // NOTE: when we create the tweak bar, either load in scene 1 or default, depending // on whether we were passing a pair of shaders if (createTweakBar(gctx, (gctx->vertFname==NULL?1:0))) { fprintf(stderr, "%s: AntTweakBar problem:\n", me); spotErrorPrint(); spotErrorClear(); TwTerminate(); glfwTerminate(); exit(1); } glfwSetWindowSizeCallback(callbackResize); glfwSetKeyCallback(callbackKeyboard); glfwSetMousePosCallback(callbackMousePos); glfwSetMouseButtonCallback(callbackMouseButton); /* Redirect GLFW mouse wheel events directly to AntTweakBar */ glfwSetMouseWheelCallback((GLFWmousewheelfun)TwEventMouseWheelGLFW); /* Redirect GLFW char events directly to AntTweakBar */ glfwSetCharCallback((GLFWcharfun)TwEventCharGLFW); /* Main loop */ while (gctx->running) { // NOTE: we update UVN every step updateUVN(gctx->camera.uvn, gctx->camera.at, gctx->camera.from, gctx->camera.up); // Update time if (!gctx->paused) { gctx->time += 0.1; if (gctx->time == 10) { gctx->time = 0; } } /* render */ if (contextDraw(gctx)) { fprintf(stderr, "%s: trouble drawing:\n", me); spotErrorPrint(); spotErrorClear(); /* Can comment out "break" so that OpenGL bugs are reported but do not lead to the termination of the program */ /* break; */ } /* Draw tweak bar last, just prior to buffer swap */ if (!TwDraw()) { fprintf(stderr, "%s: AntTweakBar error: %s\n", me, TwGetLastError()); break; } /* Display rendering results */ glfwSwapBuffers(); /* NOTE: don't call glfwWaitEvents() if you want to redraw continuously */ // glfwWaitEvents(); /* quit if window was closed */ if (!glfwGetWindowParam(GLFW_OPENED)) { gctx->running = 0; } } contextGLDone(gctx); contextNix(gctx); TwTerminate(); glfwTerminate(); exit(0); }
int main() { SDL_Window *window = NULL; int width = 480, height = 480; int flags; int quit = 0; // Initialize SDL, then get the current video mode and use it to create a SDL window. if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Video initialization failed: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } // Request GL context to be OpenGL 3.2 Core Profile SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); // Other GL attributes SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN; window = SDL_CreateWindow("AntTweakBar example using OpenGL Core Profile and SDL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags); if (window == NULL) { fprintf(stderr, "Video mode set failed: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } // Initialize AntTweakBar if (!TwInit(TW_OPENGL_CORE, NULL)) { fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError()); SDL_Quit(); exit(1); } // Tell the window size to AntTweakBar TwWindowSize(width, height); // Create a tweak bar CreateTweakBar(); // Set OpenGL viewport glViewport(0, 0, width, height); // Prepare GL shaders and programs for drawing InitRender(); // Main loop: // - Draw scene // - Process events while (!quit) { SDL_Event event; int handled; GLenum error; // Clear screen glClearColor(0.5f, 0.75f, 0.8f, 1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Update angle and draw geometry angle = (float)SDL_GetTicks()/25.0f * (FLOAT_PI/180.0f); quat[0] = quat[1] = 0; quat[2] = (float)sin(angle/2.0f); quat[3] = (float)cos(angle/2.0f); Render(); // Draw tweak bars TwDraw(); // Present frame buffer SDL_GL_SwapWindow(window); // Process incoming events while (SDL_PollEvent(&event)) { // Send event to AntTweakBar handled = TwEventSDL(&event); // If event has not been handled by AntTweakBar, process it if (!handled) { switch (event.type) { case SDL_QUIT: // Window is closed quit = 1; break; case SDL_WINDOWEVENT: // Window size has changed // Resize SDL video mode if (event.window.event == SDL_WINDOWEVENT_RESIZED) { width = event.window.data1; height = event.window.data2; // Resize OpenGL viewport glViewport(0, 0, width, height); // Restore OpenGL states InitRender(); // TwWindowSize has been called by TwEventSDL, // so it is not necessary to call it again here. } break; } } } while ((error = glGetError()) != GL_NO_ERROR) fprintf(stderr, "GL error detected: 0x%04X\n", error); } // End of main loop // Terminate AntTweakBar TwTerminate(); // Delete GL shaders and buffer UninitRender(); // Terminate SDL SDL_Quit(); return 0; }
int32 App::Run() { try { if(createConsole) { Win32Call(AllocConsole()); Win32Call(SetConsoleTitle(applicationName.c_str())); FILE* consoleFile = nullptr; freopen_s(&consoleFile, "CONOUT$", "wb", stdout); } window.SetClientArea(deviceManager.BackBufferWidth(), deviceManager.BackBufferHeight()); deviceManager.Initialize(window); if(showWindow) window.ShowWindow(); blendStates.Initialize(deviceManager.Device()); rasterizerStates.Initialize(deviceManager.Device()); depthStencilStates.Initialize(deviceManager.Device()); samplerStates.Initialize(deviceManager.Device()); // Create a font + SpriteRenderer font.Initialize(L"Arial", 18, SpriteFont::Regular, true, deviceManager.Device()); spriteRenderer.Initialize(deviceManager.Device()); Profiler::GlobalProfiler.Initialize(deviceManager.Device(), deviceManager.ImmediateContext()); window.RegisterMessageCallback(WM_SIZE, OnWindowResized, this); // Initialize AntTweakBar TwCall(TwInit(TW_DIRECT3D11, deviceManager.Device())); // Create a tweak bar tweakBar = TwNewBar("Settings"); std::string helpTextDefinition = MakeAnsiString(" GLOBAL help='%s' ", globalHelpText.c_str()); TwCall(TwDefine(helpTextDefinition.c_str())); TwCall(TwDefine(" GLOBAL fontsize=3 ")); Settings.Initialize(tweakBar); TwHelper::SetValuesWidth(Settings.TweakBar(), 120, false); AppSettings::Initialize(deviceManager.Device()); Initialize(); AfterReset(); while(window.IsAlive()) { if(!window.IsMinimized()) { timer.Update(); Settings.Update(); CalculateFPS(); AppSettings::Update(); Update(timer); UpdateShaders(deviceManager.Device()); AppSettings::UpdateCBuffer(deviceManager.ImmediateContext()); Render(timer); // Render the profiler text spriteRenderer.Begin(deviceManager.ImmediateContext(), SpriteRenderer::Point); Profiler::GlobalProfiler.EndFrame(spriteRenderer, font); spriteRenderer.End(); { PIXEvent pixEvent(L"Ant Tweak Bar"); // Render the TweakBar UI TwCall(TwDraw()); } deviceManager.Present(); } window.MessageLoop(); } } catch(SampleFramework11::Exception exception) { exception.ShowErrorMessage(); return -1; } ShutdownShaders(); TwCall(TwTerminate()); if(createConsole) { fclose(stdout); FreeConsole(); } return returnCode; }
MillerRender::MillerRender() { gLookAtOther = true; gPosition1 = vec3(-1.5f, 0.0f, 0.0f); // gOrientation1; // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); //return -1;exit } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context window = glfwCreateWindow( 1024, 768, "Tutorial 17 - Rotations", NULL, NULL); if( window == NULL ){ fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" ); glfwTerminate(); // return -1;exit } glfwMakeContextCurrent(window); // Initialize GLEW glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); // return -1; exit } //initGL(window); // Initialize the GUI TwInit(TW_OPENGL_CORE, NULL); TwWindowSize(1024, 768); TwBar * EulerGUI = TwNewBar("Euler settings"); // TwBar * QuaternionGUI = TwNewBar("Quaternion settings"); TwSetParam(EulerGUI, NULL, "refresh", TW_PARAM_CSTRING, 1, "0.1"); // TwSetParam(QuaternionGUI, NULL, "position", TW_PARAM_CSTRING, 1, "808 16"); TwAddVarRW(EulerGUI, "Euler X", TW_TYPE_FLOAT, &gOrientation1.x, "step=0.01"); TwAddVarRW(EulerGUI, "Euler Y", TW_TYPE_FLOAT, &gOrientation1.y, "step=0.01"); TwAddVarRW(EulerGUI, "Euler Z", TW_TYPE_FLOAT, &gOrientation1.z, "step=0.01"); TwAddVarRW(EulerGUI, "Pos X" , TW_TYPE_FLOAT, &gPosition1.x, "step=0.1"); TwAddVarRW(EulerGUI, "Pos Y" , TW_TYPE_FLOAT, &gPosition1.y, "step=0.1"); TwAddVarRW(EulerGUI, "Pos Z" , TW_TYPE_FLOAT, &gPosition1.z, "step=0.1"); //TwAddVarRW(QuaternionGUI, "Quaternion", TW_TYPE_QUAT4F, &gOrientation2, "showval=true open=true "); //TwAddVarRW(QuaternionGUI, "Use LookAt", TW_TYPE_BOOL8 , &gLookAtOther, "help='Look at the other monkey ?'"); // Set GLFW event callbacks. I removed glfwSetWindowSizeCallback for conciseness glfwSetMouseButtonCallback(window, (GLFWmousebuttonfun)TwEventMouseButtonGLFW); // - Directly redirect GLFW mouse button events to AntTweakBar glfwSetCursorPosCallback(window, (GLFWcursorposfun)TwEventMousePosGLFW); // - Directly redirect GLFW mouse position events to AntTweakBar glfwSetScrollCallback(window, (GLFWscrollfun)TwEventMouseWheelGLFW); // - Directly redirect GLFW mouse wheel events to AntTweakBar glfwSetKeyCallback(window, (GLFWkeyfun)TwEventKeyGLFW); // - Directly redirect GLFW key events to AntTweakBar glfwSetCharCallback(window, (GLFWcharfun)TwEventCharGLFW); // - Directly redirect GLFW char events to AntTweakBar // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetCursorPos(window, 1024/2, 768/2); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); // Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE); // Read our .obj file std::vector<unsigned short> indices; std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_uvs; std::vector<glm::vec3> indexed_normals; // load model //char* file = "/home/kaeon/MyProgram/src/rim.stl"; //char* file = "/home/kaeon/MyProgram/src/box.stl"; char* file = "/home/kaeon/MyProgram/OpenGL-33-myproject/src/cube.obj"; //char* file = "/home/kaeon/MyProgram/OpenGL-33-myproject/src/ES4.STL"; //char* file = "/home/kaeon/MyProgram/src/suzanne.obj"; //char* file = "/home/kaeon/MyProgram/src/monkey.obj"; //loadOBJ(file,outIndices,vertexArray,uvArray,normalArray); //bool res = loadAssImp(file, indices, indexed_vertices, indexed_uvs, indexed_normals); loadOBJ(file, indices,indexed_vertices,indexed_uvs,indexed_normals); ChangeVerticesCoord(indexed_vertices); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); GLuint WP_VertexArrayID; glGenVertexArrays(1, &WP_VertexArrayID); glBindVertexArray(WP_VertexArrayID); // Create and compile our GLSL program from the shaders //GLuint programID = LoadShaders( "/home/kaeon/MyProgram/opengl_test_success/SimpleTransform.vertexshader", "/home/kaeon/MyProgram/opengl_test_success/SingleColor.fragmentshader" ); programID = LoadShaders( "/home/kaeon/MyProgram/OpenGL-33-myproject/src/StandardShading.vertexshader", "/home/kaeon/MyProgram/OpenGL-33-myproject/src/StandardShading.fragmentshader" ); // Get a handle for our "MVP" uniform MatrixID = glGetUniformLocation(programID, "MVP"); ViewMatrixID = glGetUniformLocation(programID, "V"); ModelMatrixID = glGetUniformLocation(programID, "M"); // Load the texture Texture = loadDDS("/home/kaeon/MyProgram/OpenGL-33-myproject/src/uvmap.DDS"); // Get a handle for our "myTextureSampler" uniform TextureID = glGetUniformLocation(programID, "myTextureSampler"); /***==================== My triangle=============================e **/ std::vector<unsigned short> indices2;//(101*101); std::vector<glm::vec3> indexed_vertices2;//(101*101); std::vector<glm::vec2> indexed_uvs2; std::vector<glm::vec3> indexed_normals2; // /* for (int i = 0; i < 101; i++) { for (int j = 0; j < 101; j++) { double z = sin(float(i)/10.0)*sin(float(i)/10.0); indexed_vertices2[i] = glm::vec3( i-50, j-50, z-20.0); } }*/ // CalculateIndices(indices2); // calculate indices //loadOBJ("/home/kaeon/MyProgram/OpenGL-33-myproject/src/ES4.STL", indices2,indexed_vertices2,indexed_uvs2,indexed_normals2); loadOBJ("/home/kaeon/MyProgram/OpenGL-33-myproject/src/cube.obj", indices2,indexed_vertices2,indexed_uvs2,indexed_normals2); ChangeVerticesCoord(indexed_vertices2); /***==================================================================**/ // Load it into a VBO GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); // glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, (indexed_vertices.size() + indexed_vertices2.size()) * sizeof(glm::vec3), 0, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0 ,indexed_vertices.size()*sizeof(glm::vec3), &indexed_vertices[0] ); glBufferSubData(GL_ARRAY_BUFFER, indexed_vertices.size()*sizeof(glm::vec3), indexed_vertices2.size()*sizeof(glm::vec3), &indexed_vertices2[0]); GLuint uvbuffer; glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); //glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(glm::vec2), &indexed_uvs[0], GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, (indexed_uvs.size()+indexed_uvs2.size() )* sizeof(glm::vec2), 0, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0 ,indexed_uvs.size()*sizeof(glm::vec2), &indexed_uvs[0] ); glBufferSubData(GL_ARRAY_BUFFER, indexed_uvs.size()*sizeof(glm::vec2), indexed_uvs2.size()*sizeof(glm::vec2), &indexed_uvs2[0]); GLuint normalbuffer; glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); //glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, (indexed_normals.size()+indexed_normals2.size() )* sizeof(glm::vec3), 0, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0 ,indexed_normals.size()*sizeof(glm::vec3), &indexed_normals[0] ); glBufferSubData(GL_ARRAY_BUFFER, indexed_normals.size()*sizeof(glm::vec3), indexed_normals2.size()*sizeof(glm::vec3), &indexed_normals2[0]); // Generate a buffer for the indices as well GLuint elementbuffer; glGenBuffers(1, &elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0] , GL_STATIC_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (indices.size()+indices2.size() )* sizeof(unsigned short), 0, GL_STATIC_DRAW); glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0 ,indices.size()*sizeof(unsigned short), &indices[0] ); glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, indices.size()*sizeof(unsigned short), indices2.size()*sizeof(unsigned short), &indices2[0]); // Get a handle for our "LightPosition" uniform glUseProgram(programID); GLuint LightID = glGetUniformLocation(programID, "LightPosition_worldspace"); // For speed computation double lastTime = glfwGetTime(); double lastFrameTime = lastTime; int nbFrames = 0; std::cout<<"test0"<<std::endl; float tt = 0.0; do{ // Measure speed double currentTime = glfwGetTime(); float deltaTime = (float)(currentTime - lastFrameTime); lastFrameTime = currentTime; nbFrames++; if ( currentTime - lastTime >= 1.0 ){ // If last prinf() was more than 1sec ago // printf and reset printf("%f ms/frame\n", 1000.0/double(nbFrames)); nbFrames = 0; lastTime += 1.0; } // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Use our shader glUseProgram(programID); /* // Compute the MVP matrix from keyboard and mouse input // computeMatricesFromInputs(); glm::mat4 ProjectionMatrix = getProjectionMatrix(); glm::mat4 ViewMatrix = getViewMatrix(); glm::mat4 ModelMatrix = glm::mat4(1.0); glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); */ glm::mat4 ProjectionMatrix = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 110.0f);// display range glm::mat4 ViewMatrix = glm::lookAt( //glm::vec3( 0, 0, 70 ), // Camera is here glm::vec3( 20,30, 70 ), // Camera is here //glm::vec3(gOrientation1.x,0,0),// and looks here glm::vec3( 0, 0, 0 ), // and looks here //glm::vec3( 0, 1, 0 ) // Head is up (set to 0,-1,0 to look upside-down) glm::vec3( 3, 10, 5 ) // Head is up (set to 0,-1,0 to look upside-down) ); glm::vec3 lightPos = glm::vec3(gPosition1.x,2,10); //glm::vec3 lightPos = glm::vec3(0,2,10); glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(TextureID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer( 1, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); { // Euler // As an example, rotate arount the vertical axis at 180\B0/sec /* gOrientation1.z += 3.14159f/2.0f * deltaTime * 5; gOrientation1.x = 3.14159f/2; gPosition1.y = 40; // Build the model matrix glm::mat4 RotationMatrix = eulerAngleYXZ(gOrientation1.y, gOrientation1.x, gOrientation1.z); glm::mat4 TranslationMatrix = translate(mat4(), gPosition1); // A bit to the left glm::mat4 ScalingMatrix = scale(mat4(), vec3(1.0f, 1.0f, 1.0f)); glm::mat4 ModelMatrix = TranslationMatrix * RotationMatrix * ScalingMatrix;*/ gOrientation1.z += 3.14159f/2.0f * deltaTime; gOrientation1.x = 20;3.14159f/2; gPosition1.y = 10; tt = tt + 0.01f; gPosition1.x = 20.0*sin(tt); //gPosition1.z = tt;//20.0*sin(tt); // Build the model matrix glm::mat4 RotationMatrix = eulerAngleYXZ(gOrientation1.y, gOrientation1.x, gOrientation1.z); glm::mat4 TranslationMatrix = translate(mat4(), gPosition1); // A bit to the left glm::mat4 ScalingMatrix = scale(mat4(), vec3(1.0f, 1.0f, 1.0f)); glm::mat4 ModelMatrix = TranslationMatrix * RotationMatrix * ScalingMatrix; // glm::mat4 ModelMatrix = eulerAngleYXZ((float)3,(float)0,(float)0)*translate(mat4(), glm::vec3(5,0,0)) *TranslationMatrix* RotationMatrix * ScalingMatrix; glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode indices.size(), // count GL_UNSIGNED_SHORT, // type (void*)0 // element array buffer offset ); } //=============================================================================// glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)(0+indexed_vertices.size()*sizeof(glm::vec3)) // array buffer offset ); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer( 1, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)(0+indexed_uvs.size()*sizeof(glm::vec2)) // array buffer offset ); // 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)(0+indexed_normals.size()*sizeof(glm::vec3)) // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); { // Euler // As an example, rotate arount the vertical axis at 180\B0/sec /* gOrientation1.z += 3.14159f/2.0f * deltaTime * 5; gOrientation1.x = 3.14159f/2; gPosition1.y = 40; // Build the model matrix glm::mat4 RotationMatrix = eulerAngleYXZ(gOrientation1.y, gOrientation1.x, gOrientation1.z); glm::mat4 TranslationMatrix = translate(mat4(), gPosition1); // A bit to the left glm::mat4 ScalingMatrix = scale(mat4(), vec3(1.0f, 1.0f, 1.0f)); glm::mat4 ModelMatrix = TranslationMatrix * RotationMatrix * ScalingMatrix;*/ gOrientation1.z += 3.14159f/2.0f * deltaTime/1000.0; gOrientation1.x = 3.14159f/2; gPosition1.y = 10;40; tt = tt + 0.01f; gPosition1.x = 20.0*sin(tt/100.0); //gPosition1.z = tt;//20.0*sin(tt); // Build the model matrix glm::mat4 RotationMatrix = eulerAngleYXZ(gOrientation1.y, gOrientation1.x, gOrientation1.z); glm::mat4 TranslationMatrix = translate(mat4(), gPosition1); // A bit to the left glm::mat4 ScalingMatrix = scale(mat4(), vec3(1.0f, 1.0f, 1.0f)); glm::mat4 ModelMatrix = TranslationMatrix * RotationMatrix * ScalingMatrix; // glm::mat4 ModelMatrix = eulerAngleYXZ((float)3,(float)0,(float)0)*translate(mat4(), glm::vec3(5,0,0)) *TranslationMatrix* RotationMatrix * ScalingMatrix; glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode indices2.size(), // count GL_UNSIGNED_SHORT, // type (void*)(0 + indices.size()) // element array buffer offset ); } //======================================================================================// glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); // Draw GUI TwDraw(); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS && glfwWindowShouldClose(window) == 0 ); // Cleanup VBO and shader glDeleteBuffers(1, &vertexbuffer); glDeleteBuffers(1, &uvbuffer); glDeleteBuffers(1, &normalbuffer); glDeleteBuffers(1, &elementbuffer); glDeleteProgram(programID); glDeleteTextures(1, &Texture); glDeleteVertexArrays(1, &VertexArrayID); glDeleteVertexArrays(1, &WP_VertexArrayID); }
// Render everything in the scene void CScene::RenderScene() { // Clear the back buffer - before drawing the geometry clear the entire window to a fixed colour float ClearColor[4] = { 0.2f, 0.2f, 0.3f, 1.0f }; // Good idea to match background to ambient colour mpd3dDeviceContext->ClearRenderTargetView( RenderTargetView, ClearColor ); mpd3dDeviceContext->ClearDepthStencilView( DepthStencilView, D3D10_CLEAR_DEPTH | D3D10_CLEAR_STENCIL , 1.0f, 0 ); // Clear the depth buffer too // Pass the camera's matrices to the vertex shader ViewMatrixVar->SetMatrix( (float*)&Camera.GetViewMatrix() ); ProjMatrixVar->SetMatrix( (float*)&Camera.GetProjectionMatrix() ); //pass the camera position //V3 temp = XMF3ToFloat3( Camera->GetPosition() ); //DirectX::XMFLOAT3 temp = Camera.GetPosition(); dxCameraPos->SetRawValue( &Camera.GetPosition(), 0, 12); //pass the lighting colours //temp = XMF3ToFloat3( AmbientColour ); dxAmbientColour->SetRawValue( &AmbientColour, 0, 12 ); SetLights( DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f), mpLights, miNumLights); //--------------------------- // Render each model DrawAllObjects(false); mp_openSquares.RenderBatch(WorldMatrixVar, ModelColourVar); mp_walls.RenderBatch( WorldMatrixVar, ModelColourVar ); mp_pathModel.RenderBatch(WorldMatrixVar, ModelColourVar); mp_splineModel.RenderBatch(WorldMatrixVar, ModelColourVar); mp_heavyTurretModel.RenderBatch(WorldMatrixVar, ModelColourVar); mp_mediumTurretModel.RenderBatch(WorldMatrixVar, ModelColourVar); mp_lightTurretModel.RenderBatch(WorldMatrixVar, ModelColourVar); mpSpriteBatch->Begin(); //mpSpriteFont->DrawString( mpSpriteBatch, L"Hello, world!", DirectX::XMFLOAT2( 500.0f, 500.0f ) ); FontRect.bottom = 0; FontRect.right = 0; if( mb_showBaseIM ) { DisplayText( "Base Influence Map", 0); DisplayMapText(BASE_OFFSET); } if( mb_showBase2IM ) { DisplayText( "Base 2 Influence Map", 0); DisplayMapText(BASE2_OFFSET); } if( mb_showCost ) { DisplayText( "Square Cost", 0); DisplayMapText(COST_OFFSET); } if( mb_showHTIM ) { DisplayText( "Heavy Turret Influence Map", 0 ); DisplayMapText(HEAVY_OFFSET); } if( mb_showLTIM ) { DisplayText( "Light Turret Influence Map", 0); DisplayMapText(LIGHT_OFFSET); } if( mb_showMTIM ) { DisplayText( "Medium Turret Influence Map", 0); DisplayMapText(MEDIUM_OFFSET); } if( mb_showPathIM ) { DisplayText( "Path Influence Map", 0 ); DisplayMapText( PATH_OFFSET); } if( mb_showWallIM ) { DisplayText( "Wall Influence Map", 0); DisplayMapText(WALL_OFFSET); } mpSpriteBatch->End(); TwDraw(); //--------------------------- // Display the Scene // After we've finished drawing to the off-screen back buffer, we "present" it to the front buffer (the screen) SwapChain->Present( 0, 0 ); }
int main (int argc, const char * argv[]) { TwBar *myBar; float bgColor[] = { 0.0f, 0.0f, 0.0f, 0.1f }; glm::mat4 mat; float axis[] = { 0.7f, 0.7f, 0.7f }; // initial model rotation float angle = 0.8f; double FT = 0; double FPS = 0; double starting = 0.0; double ending = 0.0; int rate = 0; int fr = 0; zNear = 0.1f; zFar = 100.0f; FOV = 45.0f; // Current time double time = 0; // initialise GLFW int running = GL_TRUE; if (!glfwInit()) { exit(EXIT_FAILURE); } //only for OpenGL 2.1 #ifdef USE_OPENGL21 glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1); #endif //Only for OpenGL 3.2 #ifdef USE_OPENGL32 glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1); #endif GLFWvidmode mode; glfwGetDesktopMode(&mode); if( !glfwOpenWindow(windowWidth, windowHeight, mode.RedBits, mode.GreenBits, mode.BlueBits, 0, 32, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) ) { glfwTerminate(); exit(EXIT_FAILURE); } glfwEnable(GLFW_MOUSE_CURSOR); glfwEnable(GLFW_KEY_REPEAT); // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); glfwSetMousePos(windowWidth/2, windowHeight/2); glfwSetWindowTitle("Chapter-11"); // Initialize AntTweakBar if ( !TwInit(TW_OPENGL_CORE, NULL)) { fprintf(stderr,"AntweakBar initialiazation failed: %s\n",TwGetLastError()); exit(1); } // Create a tweak bar myBar = TwNewBar("TweakBar"); //init GLEW and basic OpenGL information // VERY IMPORTANT OTHERWISE GLEW CANNOT HANDLE GL3 #ifdef USE_OPENGL32 glewExperimental = true; #endif glewInit(); std::cout<<"\nUsing GLEW "<<glewGetString(GLEW_VERSION)<<std::endl; if (GLEW_VERSION_2_1) { std::cout<<"\nYay! OpenGL 2.1 is supported and GLSL 1.2!\n"<<std::endl; } if (GLEW_VERSION_3_2) { std::cout<<"Yay! OpenGL 3.2 is supported and GLSL 1.5!\n"<<std::endl; } /* This extension defines an interface that allows various types of data (especially vertex array data) to be cached in high-performance graphics memory on the server, thereby increasing the rate of data transfers. Chunks of data are encapsulated within "buffer objects", which conceptually are nothing more than arrays of bytes, just like any chunk of memory. An API is provided whereby applications can read from or write to buffers, either via the GL itself (glBufferData, glBufferSubData, glGetBufferSubData) or via a pointer to the memory. */ if (glewIsSupported("GL_ARB_vertex_buffer_object")) std::cout<<"ARB VBO's are supported"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_buffer_object")) std::cout<<"APPLE VBO's are supported"<<std::endl; else std::cout<<"VBO's are not supported,program will not run!!!"<<std::endl; /* This extension introduces named vertex array objects which encapsulate vertex array state on the client side. The main purpose of these objects is to keep pointers to static vertex data and provide a name for different sets of static vertex data. By extending vertex array range functionality this extension allows multiple vertex array ranges to exist at one time, including their complete sets of state, in manner analogous to texture objects. GenVertexArraysAPPLE creates a list of n number of vertex array object names. After creating a name, BindVertexArrayAPPLE associates the name with a vertex array object and selects this vertex array and its associated state as current. To get back to the default vertex array and its associated state the client should bind to vertex array named 0. */ if (glewIsSupported("GL_ARB_vertex_array_object")) std::cout<<"ARB VAO's are supported\n"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_array_object"))//this is the name of the extension for GL2.1 in MacOSX std::cout<<"APPLE VAO's are supported\n"<<std::endl; else std::cout<<"VAO's are not supported, program will not run!!!\n"<<std::endl; std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl; std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl; std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl; std::ostringstream stream1,stream2; stream1 << glGetString(GL_VENDOR); stream2 << glGetString(GL_RENDERER); std::string vendor ="Title : Chapter-11 Vendor : " + stream1.str() + " Renderer : " +stream2.str(); const char *tit = vendor.c_str(); glfwSetWindowTitle(tit); // Set GLFW event callbacks // - Redirect window size changes to the callback function WindowSizeCB glfwSetWindowSizeCallback(WindowSizeCB); // - Directly redirect GLFW mouse button events to AntTweakBar glfwSetMouseButtonCallback((GLFWmousebuttonfun)TwEventMouseButtonGLFW); // - Directly redirect GLFW mouse position events to AntTweakBar glfwSetMousePosCallback((GLFWmouseposfun)TwEventMousePosGLFW); // - Directly redirect GLFW mouse wheel events to AntTweakBar glfwSetMouseWheelCallback((GLFWmousewheelfun)TwEventMouseWheelGLFW); // - Directly redirect GLFW key events to AntTweakBar glfwSetKeyCallback((GLFWkeyfun)TwEventKeyGLFW); // - Directly redirect GLFW char events to AntTweakBar glfwSetCharCallback((GLFWcharfun)TwEventCharGLFW); TwDefine("TweakBar label='Main TweakBar' alpha=0 help='Use this bar to control the objects of the scene.' "); // Add 'wire' to 'myBar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w]. TwAddVarRW(myBar, "wireframe mode", TW_TYPE_BOOL32, &wireFrame," label='Wireframe mode' key=w help='Toggle wireframe display mode.' "); // Add 'bgColor' to 'myBar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color) TwAddVarRW(myBar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' "); // Add 'Rotation' to 'myBar': this is a variable of type TW_TYPE_QUAT4F which defines the scene's orientation TwAddVarRW(myBar, "SceneRotation", TW_TYPE_QUAT4F, &Rotation," label='Scene rotation' opened=true help='Change the scenes orientation.' "); TwAddButton(myBar, "Reset", ResetView,NULL," label='Reset View' "); TwAddVarRW(myBar, "Near Clip Plane", TW_TYPE_FLOAT, &zNear,"min=0.5 max=100 step=0.5 label='Near Clip' group='Projection Properties'"); TwAddVarRW(myBar, "Far Clip Plane", TW_TYPE_FLOAT, &zFar," min=0.5 max=1000 step=0.5 label='Far Clip' group='Projection Properties'"); TwAddVarRW(myBar, "Field of View", TW_TYPE_FLOAT, &FOV," label='FoV' readonly=true group='Projection Properties'"); TwAddVarRW(myBar, "MS per 1 Frame" , TW_TYPE_DOUBLE, &FPS, "label='MS per 1 Frame' readonly=true group='Frame Rate'"); TwAddVarRW(myBar, "Frames Per Second" , TW_TYPE_INT32, &rate, "label='FPS' readonly=true group='Frame Rate'"); TwAddVarRW(myBar, "vSYNC" , TW_TYPE_BOOL8, &SYNC, "label='vSync' readonly=true group='Frame Rate'"); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); initPlane(); //initialize Plane init3Dmodel(); // initialize 3D model create_Bump_bar(); GLfloat rat = 0.001f; if(SYNC == false) { rat = 0.001f; } else { rat = 0.01f; } // Initialize time time = glfwGetTime(); double currentTime; float lastTime = 0.0f; int Frames = 0; double LT = glfwGetTime(); starting = glfwGetTime(); setVSync(SYNC); while (running) { glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); glClearColor( bgColor[0], bgColor[1], bgColor[2], bgColor[3]); //black color FOV = initialFoV - 5 * glfwGetMouseWheel(); if(camera == true) { glfwGetMousePos(&xpos,&ypos); glfwSetMousePos(windowWidth/2, windowHeight/2); horizAngle += mouseSpeedo * float(windowWidth/2 - xpos ); verticAngle += mouseSpeedo * float( windowHeight/2 - ypos ); } glm::vec3 direction(cos(verticAngle) * sin(horizAngle),sin(verticAngle),cos(verticAngle) * cos(horizAngle)); glm::vec3 right = glm::vec3(sin(horizAngle - 3.14f/2.0f),0,cos(horizAngle - 3.14f/2.0f)); glm::vec3 up = glm::cross( right, direction ); currentTime = glfwGetTime(); float dTime = float(currentTime - lastTime); lastTime = (float)currentTime; // Move forward if (glfwGetKey( GLFW_KEY_UP ) == GLFW_PRESS){ pos += direction * dTime* speedo; } // Move backward if (glfwGetKey( GLFW_KEY_DOWN ) == GLFW_PRESS){ pos -= direction * dTime * speedo; } // Strafe right if (glfwGetKey( GLFW_KEY_RIGHT ) == GLFW_PRESS){ pos += right * dTime * speedo; } //Strafe left if (glfwGetKey( GLFW_KEY_LEFT ) == GLFW_PRESS){ pos -= right * dTime * speedo; } if (glfwGetKey(GLFW_KEY_SPACE) == GLFW_PRESS){ if(camera == false) { camera=true; glfwSetMousePos(windowWidth/2, windowHeight/2); glfwGetMousePos(&xpos,&ypos); } else { camera=false; glfwSetMousePos(windowWidth/2, windowHeight/2); glfwGetMousePos(&xpos,&ypos); } } mat = ConvertQuaternionToMatrix(Rotation, mat); glm::mat4 cube; glm::mat4 translateMat = glm::mat4(); translateMat = glm::translate(translateMat,glm::vec3(5.0,3.0,4.0)); cube = mat * translateMat; displayPlane(mat,pos,direction,up); display3Dmodel(cube,mat,pos,direction,up); // drawing the AntWeakBar if (wireFrame) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); TwDraw(); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); TwDraw(); } fr++; ending = glfwGetTime(); if(ending - starting >= 1) { rate = fr; fr = 0; starting = glfwGetTime(); } double CT = glfwGetTime(); Frames++; if(CT -LT >= 1.0) { FPS = 1000.0 / (double)Frames; Frames = 0; LT += 1.0f; } glfwSwapBuffers(); //check if ESC was pressed running=!glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED); } //close OpenGL window and terminate AntTweakBar and GLFW TwTerminate(); glfwTerminate(); exit(EXIT_SUCCESS); }
void draw() { rmt_LogText("start profiling"); //rmt_BeginCPUSample(uv_run); uv_run(uv_default_loop(), UV_RUN_NOWAIT); //rmt_EndCPUSample(); CUstream stream0 = 0; rmt_BeginCUDASample(main, stream0); { if (isResized()) { setupSizeResource(); } // Launch the Vector Add CUDA Kernel int threadsPerBlock = 256; int blocksPerGrid = (img.width * img.height + threadsPerBlock - 1) / threadsPerBlock; //printf("CUDA kernel launch with %d blocks of %d threads\n", blocksPerGrid, threadsPerBlock); dim3 blockDim = { 32, 32, 1 }; dim3 gridDim = { width / blockDim.x, height / blockDim.y, 1 }; float3 iResolution = { width, height, 1 }; float iGlobalTime = glfwGetTime(); float4 iMouse = { mouseX, mouseY, mouseX, mouseY }; rmt_BeginCUDASample(cuMemcpyHtoD, stream0); checkCudaErrors(cuMemcpyHtoD(d_iResolution, &iResolution, sizeof iResolution)); checkCudaErrors(cuMemcpyHtoD(d_iGlobalTime, &iGlobalTime, sizeof iGlobalTime)); checkCudaErrors(cuMemcpyHtoD(d_iMouse, &iMouse, sizeof iMouse)); rmt_EndCUDASample(stream0); rmt_BeginCUDASample(cuLaunchKernel, stream0); checkCudaErrors(cuLaunchKernel(kernel_addr, gridDim.x, gridDim.y, gridDim.z, /* grid dim */ blockDim.x, blockDim.y, blockDim.z, /* block dim */ 0, 0, /* shared mem, stream */ 0, /* arguments */ 0)); rmt_EndCUDASample(stream0); rmt_BeginCUDASample(cuCtxSynchronize, stream0); checkCudaErrors(cuCtxSynchronize()); rmt_EndCUDASample(stream0); rmt_BeginCUDASample(cuMemcpyDtoH, stream0); checkCudaErrors(cuMemcpyDtoH(img_content, d_img_content, item_size)); rmt_EndCUDASample(stream0); } rmt_EndCUDASample(stream0); rmt_BeginOpenGLSample(main); { background(color(0,0,0)); updateImage(img, img_content); image(img, 0, 0, width, height); TwDraw(); } rmt_EndOpenGLSample(); rmt_LogText("end profiling"); }