void GenTexture(const SDL_Surface * surface, const TEXTUREINFO & info, GLuint & id, bool & alphachannel, std::ostream & error) { //detect channels bool compression = (surface->w > 512 || surface->h > 512) && !info.normalmap; bool srgb = info.srgb; int format; int internalformat = compression ? (srgb ? GL_COMPRESSED_SRGB : GL_COMPRESSED_RGB) : (srgb ? GL_SRGB8 : GL_RGB); switch (surface->format->BytesPerPixel) { case 1: format = GL_LUMINANCE; internalformat = compression ? GL_COMPRESSED_LUMINANCE : GL_LUMINANCE; alphachannel = false; break; case 2: format = GL_LUMINANCE_ALPHA; internalformat = compression ? GL_COMPRESSED_LUMINANCE_ALPHA : GL_LUMINANCE_ALPHA; alphachannel = true; break; case 3: #ifdef __APPLE__ format = GL_BGR; #else format = GL_RGB; #endif internalformat = compression ? (srgb ? GL_COMPRESSED_SRGB : GL_COMPRESSED_RGB) : (srgb ? GL_SRGB8 : GL_RGB); alphachannel = false; break; case 4: #ifdef __APPLE__ format = GL_BGRA; #else format = GL_RGBA; #endif internalformat = compression ? (srgb ? GL_COMPRESSED_SRGB_ALPHA : GL_COMPRESSED_RGBA) : (srgb ? GL_SRGB8_ALPHA8 : GL_RGBA); alphachannel = true; break; default: #ifdef __APPLE__ format = GL_BGR; #else format = GL_RGB; #endif break; } glGenTextures(1, &id); OPENGL_UTILITY::CheckForOpenGLErrors("Texture ID generation", error); // Create MipMapped Texture glBindTexture(GL_TEXTURE_2D, id); if (info.repeatu) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); if (info.repeatv) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (info.mipmap) { if (info.nearest) { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); } if (!glGenerateMipmap) // this kind of automatic mipmap generation is deprecated in GL3, so don't use it glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); } else { if (info.nearest) { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); } } glTexImage2D( GL_TEXTURE_2D, 0, internalformat, surface->w, surface->h, 0, format, GL_UNSIGNED_BYTE, surface->pixels ); OPENGL_UTILITY::CheckForOpenGLErrors("Texture creation", error); // If we support generatemipmap, go ahead and do it regardless of the info.mipmap setting. // In the GL3 renderer the sampler decides whether or not to do mip filtering, so we conservatively make mipmaps available for all textures. if (glGenerateMipmap) glGenerateMipmap(GL_TEXTURE_2D); //check for anisotropy if (info.anisotropy > 1) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)info.anisotropy); } }
void ourInit(int Width, int Height) { int n,i,j; loadOffsets(); struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPROW row_pointer[1]; unsigned long location = 0; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); for (i = 0; i<2; i++) for (n = 0; n<NUM_PIC[i]; n++) { jpeg_stdio_src(&cinfo, fd[i][n]); jpeg_read_header(&cinfo, 0); cinfo.scale_num = 1; cinfo.scale_denom = SCALE; jpeg_start_decompress(&cinfo); wid[i][n] = cinfo.output_width; hei[i][n] = cinfo.output_height; dep[i][n] = cinfo.num_components; //should always be 3 image[i][n] = (unsigned char *) malloc(wid[i][n] * hei[i][n] * dep[i][n]); row_pointer[0] = (unsigned char *) malloc(wid[i][n] * dep[i][n]); /* read one scan line at a time */ while( cinfo.output_scanline < cinfo.output_height ) { jpeg_read_scanlines( &cinfo, row_pointer, 1 ); for( j=0; j< (wid[i][n] * dep[i][n]); j++) image[i][n][location++] = row_pointer[0][j]; } location = 0; fclose(fd[i][n]); jpeg_finish_decompress(&cinfo); } jpeg_destroy_decompress(&cinfo); ourBuildTextures(); // Color to clear color buffer to. glClearColor(0.1f, 0.1f, 0.1f, 0.0f); // Depth to clear depth buffer to; type of test. glClearDepth(1.0); glDepthFunc(GL_LESS); // Enables Smooth Color Shading; try GL_FLAT for (lack of) fun. glShadeModel(GL_SMOOTH); // Load up the correct perspective matrix; using a callback directly. cbResizeScene(Width,Height); // Set up a light, turn it on. glLightfv(GL_LIGHT1, GL_POSITION, Light_Position); glLightfv(GL_LIGHT1, GL_AMBIENT, Light_Ambient); // glLightfv(GL_LIGHT1, GL_DIFFUSE, Light_Diffuse); glEnable (GL_LIGHT1); // A handy trick -- have surface material mirror the color. glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glutSetCursor(GLUT_CURSOR_NONE); glEnable(GL_TEXTURE_RECTANGLE_ARB); glDisable(GL_LIGHTING); glEnable(GL_LIGHTING); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); // If we're blending, we don't want z-buffering. glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); }
void intro_init( void ) { // create openGL functions for (int i=0; i<NUM_GL_NAMES; i++) glFP[i] = (GenFP)wglGetProcAddress(glnames[i]); // create noise Texture #ifdef FLOAT_TEXTURE for (int i = 0; i < NOISE_TEXTURE_SIZE * NOISE_TEXTURE_SIZE * NOISE_TEXTURE_SIZE * 4; i++) { noiseData[i] = frand() - 0.5f; } #else for (int i = 0; i < NOISE_TEXTURE_SIZE * NOISE_TEXTURE_SIZE * NOISE_TEXTURE_SIZE * 4; i++) { noiseData[i] = (unsigned char)rand(); } #endif // Create and link shader and stuff: // I will have to separate these to be able to use more than one shader... // TODO: I should make some sort of compiling and linking loop... // init objects: GLuint vMainObject = glCreateShader(GL_VERTEX_SHADER); GLuint fMainBackground = glCreateShader(GL_FRAGMENT_SHADER); GLuint fOffscreenCopy = glCreateShader(GL_FRAGMENT_SHADER); shaderPrograms[0] = glCreateProgram(); shaderPrograms[1] = glCreateProgram(); // compile sources: glShaderSource(vMainObject, 1, &vertexMainObject, NULL); glCompileShader(vMainObject); glShaderSource(fMainBackground, 1, &fragmentMainBackground, NULL); glCompileShader(fMainBackground); glShaderSource(fOffscreenCopy, 1, &fragmentOffscreenCopy, NULL); glCompileShader(fOffscreenCopy); #ifdef SHADER_DEBUG // Check programs int tmp, tmp2; glGetShaderiv(vMainObject, GL_COMPILE_STATUS, &tmp); if (!tmp) { glGetShaderInfoLog(vMainObject, 4096, &tmp2, err); err[tmp2]=0; MessageBox(hWnd, err, "vMainObject shader error", MB_OK); return; } glGetShaderiv(fMainBackground, GL_COMPILE_STATUS, &tmp); if (!tmp) { glGetShaderInfoLog(fMainBackground, 4096, &tmp2, err); err[tmp2]=0; MessageBox(hWnd, err, "fMainBackground shader error", MB_OK); return; } glGetShaderiv(fOffscreenCopy, GL_COMPILE_STATUS, &tmp); if (!tmp) { glGetShaderInfoLog(fOffscreenCopy, 4096, &tmp2, err); err[tmp2]=0; MessageBox(hWnd, err, "fOffscreeCopy shader error", MB_OK); return; } #endif // link shaders: glAttachShader(shaderPrograms[0], vMainObject); glAttachShader(shaderPrograms[0], fMainBackground); glLinkProgram(shaderPrograms[0]); glAttachShader(shaderPrograms[1], vMainObject); glAttachShader(shaderPrograms[1], fOffscreenCopy); glLinkProgram(shaderPrograms[1]); // Set texture. glEnable(GL_TEXTURE_3D); // automatic? glGenTextures(1, &noiseTexture); glBindTexture(GL_TEXTURE_3D, noiseTexture); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT); #ifdef FLOAT_TEXTURE glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA32F, NOISE_TEXTURE_SIZE, NOISE_TEXTURE_SIZE, NOISE_TEXTURE_SIZE, 0, GL_RGBA, GL_FLOAT, noiseData); #else glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, NOISE_TEXTURE_SIZE, NOISE_TEXTURE_SIZE, NOISE_TEXTURE_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, noiseData); #endif // Create a rendertarget texture glGenTextures(1, &offscreenTexture); glBindTexture(GL_TEXTURE_2D, offscreenTexture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); //glBindTexture(GL_TEXTURE_2D, 0); }
void userSettings(void) { lighting(currentLighting); materials(currentMaterials); if ( lightingEnabled ) { glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } else { glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); } if ( smoothEnabled ) { glShadeModel(GL_SMOOTH); } else { glShadeModel(GL_FLOAT); } if ( idleSpin ) { glutIdleFunc(spinCube); } else { glutIdleFunc(NULL); } if ( texEnabled ) { glEnable(GL_TEXTURE_2D); } else { glDisable(GL_TEXTURE_2D); } if ( fastTexture ) { glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); } else { glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } if ( mipmapEnabled ) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } if ( fogEnabled ) { float fogColor[] = {0.7, 0.6, 0.6, 1.0}; glClearColor(fogColor[0], fogColor[1], fogColor[2], fogColor[3]); glEnable(GL_FOG); glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_DENSITY, 1.0); glFogf(GL_FOG_START, zNear); glFogf(GL_FOG_END, zFar); glFogfv(GL_FOG_COLOR, fogColor); } else { glDisable(GL_FOG); glClearColor(0.0, 0.0, 0.0, 1.0 ); } if ( lineAAEnabled ) glEnable(GL_BLEND); else glDisable(GL_BLEND); if ( lineAAEnabled ) { glEnable( GL_LINE_SMOOTH ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); } else { glDisable( GL_LINE_SMOOTH ); } if ( depthEnabled ) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if ( perspectiveXform ) { glFrustum(-1.25, 1.25, -1.25, 1.25, zNear, zFar); viewxform_z = -5.0; } else { glOrtho(-2.0, 2.0, -2.0, 2.0, zNear, zFar); viewxform_z = -5.0; } glMatrixMode(GL_MODELVIEW); }
/*********************************************************** * Name: init_textures * * Arguments: * CUBE_STATE_T *state - holds OGLES model info * * Description: Initialise OGL|ES texture surfaces to use image * buffers * * Returns: void * ***********************************************************/ static void init_textures(CUBE_STATE_T *state) { // load three texture buffers but use them on six OGL|ES texture surfaces load_tex_images(state); glGenTextures(6, &state->tex[0]); // setup first texture glBindTexture(GL_TEXTURE_2D, state->tex[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, IMAGE_SIZE, IMAGE_SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, state->tex_buf1); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLfloat)GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLfloat)GL_NEAREST); // setup second texture - reuse first image glBindTexture(GL_TEXTURE_2D, state->tex[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, IMAGE_SIZE, IMAGE_SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, state->tex_buf1); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLfloat)GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLfloat)GL_NEAREST); // third texture glBindTexture(GL_TEXTURE_2D, state->tex[2]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, IMAGE_SIZE, IMAGE_SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, state->tex_buf2); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLfloat)GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLfloat)GL_NEAREST); // fourth texture - reuse second image glBindTexture(GL_TEXTURE_2D, state->tex[3]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, IMAGE_SIZE, IMAGE_SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, state->tex_buf2); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLfloat)GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLfloat)GL_NEAREST); //fifth texture glBindTexture(GL_TEXTURE_2D, state->tex[4]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, IMAGE_SIZE, IMAGE_SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, state->tex_buf3); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLfloat)GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLfloat)GL_NEAREST); // sixth texture - reuse third image glBindTexture(GL_TEXTURE_2D, state->tex[5]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, IMAGE_SIZE, IMAGE_SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, state->tex_buf3); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLfloat)GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLfloat)GL_NEAREST); // setup overall texture environment glTexCoordPointer(2, GL_FLOAT, 0, texCoords); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_TEXTURE_2D); }
void ofxFBOTexture::allocate(int w, int h, bool autoClear, int numSamples) { _isActive = false; texData.width = w; texData.height = h; if( numSamples == 0 ){ bUseMultiSample = false; }else{ bUseMultiSample = true; } if (GLEE_ARB_texture_rectangle){ texData.tex_w = w; texData.tex_h = h; texData.textureTarget = GL_TEXTURE_RECTANGLE_ARB; } else { texData.tex_w = ofNextPow2(w); texData.tex_h = ofNextPow2(h); } if (GLEE_ARB_texture_rectangle){ texData.tex_t = w; texData.tex_u = h; } else { texData.tex_t = 1.0f; texData.tex_u = 1.0f; } // attempt to free the previous bound texture, if we can: clean(); texData.width = w; texData.height = h; texData.bFlipTexture = true; texData.glType = GL_RGBA; this->autoClear = autoClear; if( bUseMultiSample ){ // MULTISAMPLE // //THEO Create the render buffer for depth glGenRenderbuffersEXT(1, &depthBuffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthBuffer); glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, numSamples, GL_DEPTH_COMPONENT, texData.tex_w, texData.tex_h); //THEO multi sampled color buffer glGenRenderbuffersEXT(1, &colorBuffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, colorBuffer); glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, numSamples, GL_RGBA8, texData.tex_w, texData.tex_h); //THEO create fbo for multi sampled content and attach depth and color buffers to it glGenFramebuffersEXT(1, &mfbo); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mfbo); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, colorBuffer); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthBuffer); }else{ //THEO Create the render buffer for depth glGenRenderbuffersEXT(1, &depthBuffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthBuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, texData.tex_w, texData.tex_h); } // NORMAL // // create & setup texture glGenTextures(1, (GLuint *)(&texData.textureID)); // could be more then one, but for now, just one glBindTexture(texData.textureTarget, (GLuint)(texData.textureID)); glTexParameterf(texData.textureTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(texData.textureTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(texData.textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(texData.textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(texData.textureTarget, 0, texData.glType, texData.tex_w, texData.tex_h, 0, texData.glType, GL_UNSIGNED_BYTE, 0); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // create & setup FBO glGenFramebuffersEXT(1, &fbo); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); // attach it to the FBO so we can render to it glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, texData.textureTarget, (GLuint)texData.textureID, 0); if( !bUseMultiSample ){ // Attach the depth render buffer to the FBO as it's depth attachment glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthBuffer); } GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if(status != GL_FRAMEBUFFER_COMPLETE_EXT) { cout<<"glBufferTexture failed to initialize. Perhaps your graphics card doesnt support the framebuffer extension? If you are running osx prior to system 10.5, that could be the cause"<<endl; std::exit(1); } clear(0, 0, 0, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); texData.bAllocated = true; }
void OITWeightedAverage::VInit(GraphicsWindow* window) { m_width = window->getWindowWidth(); m_height = window->getWindowHeight(); // Load accumulation shader for accumulating all the transparent matrials, as well as their alphas. m_accumTransparencyShader = new GLSLProgram(); m_accumTransparencyShader->initShaderProgram("AccumTransparencyVert.glsl","","","","AccumTransparencyFrag.glsl"); // Load accumulation shader for accumulating all the transparent matrials, as well as their alphas. m_accumTransparencyBillboardsShader = new GLSLProgram(); m_accumTransparencyBillboardsShader->initShaderProgram("AccumTransparencyBillboardsVert.glsl","","","","AccumTransparencyBillboardsFrag.glsl"); // Load accumulation shader for accumulating all the transparent matrials, as well as their alphas. m_accumTransparencySmokeParticleSystemShader = new GLSLProgram(); m_accumTransparencySmokeParticleSystemShader->initShaderProgram("AccumTransparencySmokeParticleSystemVert.glsl","","","","AccumTransparencySmokeParticleSystemFrag.glsl"); // Load Weighted Average shader, which will be used for final compositing (a variation of screen filling quad shader using multiple textures). m_weightedAverageShader = new GLSLProgram(); m_weightedAverageShader->initShaderProgram("WeightedAverageVert.glsl","","","","WeightedAverageFrag.glsl"); // Load screen filling quad shader. m_screenFillingQuadShader = new GLSLProgram(); m_screenFillingQuadShader->initShaderProgram("ScreenFillingQuadVert.glsl","","","","ScreenFillingQuadFrag.glsl"); // Create framebuffer for tranparent objects overdraw count. m_accumFrameBuffer = new Framebuffer(window->getWindowWidth(),window->getWindowHeight()); m_activeColorAttachments.push_back(0); m_activeColorAttachments.push_back(1); m_accumFrameBuffer->setColorAttachment(0); m_accumFrameBuffer->setColorAttachment(1); m_accumFrameBuffer->setDepthStencilTexture(); m_accumFrameBuffer->unbind(); // Additional textures to pass for the second transparency render pass. m_additionalTexturesTransparency.push_back(m_accumFrameBuffer->getColorAttachment(0)); m_additionalTexturesTransparency.push_back(m_accumFrameBuffer->getColorAttachment(1)); // Create screen filling quad. m_compositeScreenFillingQuad = new Quad(glm::vec3(-1.0,1.0,0), glm::vec3(-1.0,-1.0,0), glm::vec3(1.0,-1.0,0), glm::vec3(1.0,1.0,0), glm::vec3(0), 0, 0, 0); m_compositeScreenFillingQuad->initQuad(); m_compositeScreenFillingQuad->setGLSLProgram(*m_screenFillingQuadShader); //m_compositeScreenFillingQuad->setTexture(m_accumFrameBuffer->getColorAttachment(0)); glGenTextures(1,&m_opaqueTextureHandle); glBindTexture(GL_TEXTURE_2D, m_opaqueTextureHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, m_width, m_height, 0, GL_RGBA, GL_FLOAT, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); m_additionalTexturesOpaque.push_back(m_opaqueTextureHandle); glGenTextures(1,&m_resultTexture); glBindTexture(GL_TEXTURE_2D, m_resultTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, m_width, m_height, 0, GL_RGBA, GL_FLOAT, NULL); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); check_gl_error(); }
void Renderer::Interpolation(const Pipeline &pipeline) { if (this->renderTarget->useFBO) glBindTexture(GL_TEXTURE_2D, renderTarget->textureID[1]); else glBindTexture(GL_TEXTURE_2D, renderTarget->textureID[0]); //Texture wrapping( clamp vs. wrap) if (pipeline.textureWrap == 0) { #ifdef USE_GLES1 glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #else glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); #endif } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } glMatrixMode(GL_TEXTURE); glLoadIdentity(); glBlendFunc(GL_SRC_ALPHA, GL_ZERO); glColor4f(1.0, 1.0, 1.0, pipeline.screenDecay); glEnable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); //glVertexPointer(2, GL_FLOAT, 0, p); //glTexCoordPointer(2, GL_FLOAT, 0, t); glInterleavedArrays(GL_T2F_V3F,0,p); if (pipeline.staticPerPixel) { for (int j = 0; j < mesh.height - 1; j++) { int base = j * mesh.width * 2 * 5; for (int i = 0; i < mesh.width; i++) { int strip = base + i * 10; p[strip] = pipeline.x_mesh[i][j]; p[strip + 1] = pipeline.y_mesh[i][j]; p[strip + 5] = pipeline.x_mesh[i][j+1]; p[strip + 6] = pipeline.y_mesh[i][j+1]; } } } else { mesh.Reset(); omptl::transform(mesh.p.begin(), mesh.p.end(), mesh.identity.begin(), mesh.p.begin(), &Renderer::PerPixel); for (int j = 0; j < mesh.height - 1; j++) { int base = j * mesh.width * 2 * 5; for (int i = 0; i < mesh.width; i++) { int strip = base + i * 10; int index = j * mesh.width + i; int index2 = (j + 1) * mesh.width + i; p[strip] = mesh.p[index].x; p[strip + 1] = mesh.p[index].y; p[strip + 5] = mesh.p[index2].x; p[strip + 6] = mesh.p[index2].y; } } } for (int j = 0; j < mesh.height - 1; j++) glDrawArrays(GL_TRIANGLE_STRIP,j* mesh.width* 2,mesh.width*2); glDisable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); }
void MSRenderer::renderFrame() { // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Get the state from QCAR and mark the beginning of a rendering section QCAR::State state = QCAR::Renderer::getInstance().begin(); // Explicitly render the Video Background QCAR::Renderer::getInstance().drawVideoBackground(); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Did we find any trackables this frame? for(int tIdx = 0; tIdx < state.getNumTrackableResults(); tIdx++) { // Get the trackable: const QCAR::TrackableResult* trackableResult = state.getTrackableResult(tIdx); QCAR::Matrix44F modelViewMatrix = QCAR::Tool::convertPose2GLMatrix(trackableResult->getPose()); MSRenderer::scalePoseMatrix(MSController::getFrameRatio(), 1, 1, &modelViewMatrix.data[0]); // get the target info void *userData = trackableResult->getTrackable().getUserData(); MSTargetInfo *info = static_cast<MSTargetInfo *>(userData); MSTexture *tex = info->getTexture(); MSModel *model = info->getModel(); // Bind texture to OpenGL if not done yet if (!tex->mHasID) { glGenTextures(1, &(tex->mTextureID)); glBindTexture(GL_TEXTURE_2D, tex->mTextureID); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->mWidth, tex->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*) tex->mData); tex->mHasID = true; } MSRenderer::multiplyMatrix(&modelViewMatrix.data[0], info->getPose(), &modelViewMatrix.data[0]); QCAR::Matrix44F modelViewProjection; MSRenderer::multiplyMatrix(&projectionMatrix.data[0], &modelViewMatrix.data[0] , &modelViewProjection.data[0]); glUseProgram(shaderProgramID); glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, model->vertices); glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, model->normals); glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, model->texCoords); glEnableVertexAttribArray(vertexHandle); glEnableVertexAttribArray(normalHandle); glEnableVertexAttribArray(textureCoordHandle); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, tex->mTextureID); glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (GLfloat*)modelViewProjection.data); glUniform1i(texSampler2DHandle, 0); glDrawElements(GL_TRIANGLES, 3*model->nFaces, GL_UNSIGNED_SHORT, model->faces); } glDisable(GL_DEPTH_TEST); glDisableVertexAttribArray(vertexHandle); glDisableVertexAttribArray(normalHandle); glDisableVertexAttribArray(textureCoordHandle); glDisable(GL_BLEND); QCAR::Renderer::getInstance().end(); }
void InitGL( void )//__END_INIT__@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@___BEGIN_INIT__ { //eyePosition[0] = 0.0; // eyePosition[1] = 0.0; //eyePosition[2] = 4.0; look_LEFT_RIGHT = 0.0; look_UP_DOWN = 0.0; //========================================================================== #ifdef WIN32 #include "cpp/setPixelFormat.cpp" #include "headerFiles/glext_Init_B.cpp" //------------------------------------- SetVSyncState(true); #endif //========================================================================================================================================================================== //==================================================================================================================== glGenTextures(1, &shadowMap_2D); glBindTexture(GL_TEXTURE_2D, shadowMap_2D); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); //-------------------------------------------------------------------------------------------------------------------- glGenFramebuffers(1, &fboId_2D); glBindFramebuffer(GL_FRAMEBUFFER, fboId_2D); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, shadowMap_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); //######################################################################################################________SHADERS //######################################################################################################________SHADERS //================================================================ //==================================================================================== #include "_MODEL_FOLDERS_/relief_TristanDean/relief_TristanDean_Init.cpp" //==================================================================================== //=================================================================================================================== #include "cubeMaps/cubeMap_INIT.cpp" glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glAlphaFunc(GL_GREATER, 0.1); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); //===================================================================================================================== }//__END_INIT__@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@___END_INIT__
bool initialize() { //cout << "Makes it to initalize!" << endl; bool loadedSuccess = true; char defualtOBJName[] = "iceRink.obj"; //Change to change the default loaded object. btCollisionShape *tempShape = NULL; btDefaultMotionState *tempMotionState = NULL; btScalar tempMass; btVector3 tempInertia; btRigidBody *tempRigidBody = NULL; //Collision Masks int shapeColidesWith = COL_WALL | COL_SHAPE; int wallColidesWith = COL_SHAPE; //TABLE globalObjCount++; Vertex *geometry; btVector3 tempVect = btVector3(0.0f, 1.0f, 0.0f); btScalar planeScaler = 3; objTriMesh = new btTriangleMesh(); loadedSuccess = loadOBJ(defualtOBJName, &geometry); if ( !loadedSuccess ) { cout << "OBJ file not found or invalid format" << endl; return false; } glGenBuffers(1, &vbo_geometry); glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry); glBufferData(GL_ARRAY_BUFFER, sizeof(geometry)*numberTriangles*3, geometry, GL_STATIC_DRAW); //Create collision Objects //Initalize the Hockey Table. tempShape = new btBvhTriangleMeshShape(objTriMesh, true); //Hockey Table //tempShape = new btStaticPlaneShape(tempVect, planeScaler); tempMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0,-15,0))); tempMass = 0; tempInertia = btVector3(0.0f, 0.0f, 0.0f); tempShape->calculateLocalInertia(tempMass, tempInertia); btRigidBody::btRigidBodyConstructionInfo shapeRigidBodyCI(tempMass, tempMotionState, tempShape, tempInertia); tempRigidBody = new btRigidBody(shapeRigidBodyCI); objectsDataList.addObject(0, tempShape, tempMotionState, tempMass, tempInertia, vbo_geometry, numberTriangles, 1, tempRigidBody); dynamicsWorld->addRigidBody(tempRigidBody, COL_WALL, wallColidesWith); tempRigidBody = NULL; delete geometry; numberTriangles = 0; delete objTriMesh; objTriMesh = new btTriangleMesh(); //cout << "Makes it past loading the table!" << endl; /* //CUBE globalObjCount++; Vertex *Cube; objTriMesh = new btTriangleMesh(); btVector3 squareVect = btVector3(0.6f, 0.6f, 0.6f); loadedSuccess = loadOBJ("Cube.obj", &Cube); if ( !loadedSuccess ) { cout << "OBJ file not found or invalid format" << endl; return false; } // Create a Vertex Buffer object to store this vertex info on the GPU glGenBuffers(1, &vbo_cube); glBindBuffer(GL_ARRAY_BUFFER, vbo_cube); glBufferData(GL_ARRAY_BUFFER, sizeof(Cube)*numberTriangles*3, Cube, GL_STATIC_DRAW); //Initalize the Cube. //tempShape = new btBvhTriangleMeshShape(objTriMesh, true);//Cube tempShape = new btBoxShape(squareVect); tempMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0.5f,4.0f,0.0f))); tempMass = 1; tempInertia = btVector3(0.0f, 0.0f, 0.0f); objectsDataList.addObject(1, tempShape, tempMotionState, tempMass, tempInertia, vbo_cube, numberTriangles, .5f); dynamicsWorld->addRigidBody(objectsDataList.getRigidBody(1), COL_SHAPE, shapeColidesWith); delete Cube; numberTriangles = 0; delete objTriMesh; objTriMesh = new btTriangleMesh(); */ //CYLINDER //Paddle 1 globalObjCount++; Vertex *cylinder; btVector3 cylinderVect = btVector3(0.6f, 0.6f, 0.6f); objTriMesh = new btTriangleMesh(); loadedSuccess = loadOBJ("Paddle.obj", &cylinder); if ( !loadedSuccess ) { cout << "OBJ file not found or invalid format" << endl; return false; } // Create a Vertex Buffer object to store this vertex info on the GPU glGenBuffers(1, &vbo_cylinder); glBindBuffer(GL_ARRAY_BUFFER, vbo_cylinder); glBufferData(GL_ARRAY_BUFFER, sizeof(cylinder)*numberTriangles*3, cylinder, GL_STATIC_DRAW); //Initalize the Cylinder //tempShape = new btBvhTriangleMeshShape(objTriMesh, true); //cylinder tempShape = new btCylinderShape(cylinderVect); tempMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(-2.0f,1.0f,2.0f))); tempMass = 1; tempInertia = btVector3(0.0f, 0.0f, 0.0f); tempShape->calculateLocalInertia(tempMass, tempInertia); btRigidBody::btRigidBodyConstructionInfo paddleOneRigidBodyCI(tempMass, tempMotionState, tempShape, tempInertia); tempRigidBody = new btRigidBody(paddleOneRigidBodyCI); objectsDataList.addObject(1, tempShape, tempMotionState, tempMass, tempInertia, vbo_cylinder, numberTriangles, .5f, tempRigidBody); dynamicsWorld->addRigidBody(tempRigidBody, COL_SHAPE, shapeColidesWith); //delete cylinder; tempRigidBody = NULL; numberTriangles = 0; delete objTriMesh; objTriMesh = new btTriangleMesh(); cout << "Loaded Paddle 1" << endl; /* //Paddle 2 globalObjCount++; Vertex *cylinder; objTriMesh = new btTriangleMesh(); loadedSuccess = loadOBJ("Paddle.obj", &cylinder); if ( !loadedSuccess ) { cout << "OBJ file not found or invalid format" << endl; return false; } Create a Vertex Buffer object to store this vertex info on the GPU glGenBuffers(1, &vbo_cylinder); glBindBuffer(GL_ARRAY_BUFFER, vbo_cylinder); glBufferData(GL_ARRAY_BUFFER, sizeof(cylinder)*numberTriangles*3, cylinder, GL_STATIC_DRAW); Initalize the Cylinder tempShape = new btBvhTriangleMeshShape(objTriMesh, true); //cylinder tempShape = new btCylinderShape(cylinderVect); tempMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(2.0f,1.0f,2.0f))); tempMass = 1; tempInertia = btVector3(0.0f, 0.0f, 0.0f); objectsDataList.addObject(2, tempShape, tempMotionState, tempMass, tempInertia, vbo_cylinder, numberTriangles, .5f); dynamicsWorld->addRigidBody(objectsDataList.getRigidBody(2), COL_SHAPE, shapeColidesWith); delete cylinder; numberTriangles = 0; delete objTriMesh; objTriMesh = new btTriangleMesh(); //SPHERE globalObjCount++; Vertex *sphere; objTriMesh = new btTriangleMesh(); btScalar sphereScaler = 1; loadedSuccess = loadOBJ("Earth.obj", &sphere); if ( !loadedSuccess ) { cout << "OBJ file not found or invalid format" << endl; return false; } // Create a Vertex Buffer object to store this vertex info on the GPU glGenBuffers(1, &vbo_sphere); glBindBuffer(GL_ARRAY_BUFFER, vbo_sphere); glBufferData(GL_ARRAY_BUFFER, sizeof(sphere)*numberTriangles*3, sphere, GL_STATIC_DRAW); //Initalize the Sphere //tempShape = new btBvhTriangleMeshShape(objTriMesh, true); //Sphere tempShape = new btSphereShape(sphereScaler); tempMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(4.0f,1.0f,1.0f))); tempMass = 1; tempInertia = btVector3(0.0f, 0.0f, 0.0f); objectsDataList.addObject(1, tempShape, tempMotionState, tempMass, tempInertia, vbo_sphere, numberTriangles, .5f); dynamicsWorld->addRigidBody(objectsDataList.getRigidBody(1), COL_SHAPE, shapeColidesWith); delete sphere; numberTriangles = 0; */ ///Walls /* globalObjCount++; btVector3 left_wall = btVector3(4.f, 4.f, 4.f); tempShape = new btBoxShape( left_wall); tempMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(11, 0, 0.0f))); tempMass = 100; tempInertia = btVector3(0.0f, 0.0f, 0.0f); objectsDataList.addObject(4, tempShape, tempMotionState, tempMass, tempInertia, 0, 1, .5f); dynamicsWorld->addRigidBody(objectsDataList.getRigidBody(4), COL_SHAPE, shapeColidesWith); globalObjCount++; btVector3 top_wall = btVector3(6.f, 6.f, 6.f); tempShape = new btBoxShape( top_wall); tempMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0, 0, 9.5f))); tempMass = 100; tempInertia = btVector3(0.0f, 0.0f, 0.0f); objectsDataList.addObject(5, tempShape, tempMotionState, tempMass, tempInertia, 0, 1, .5f); dynamicsWorld->addRigidBody(objectsDataList.getRigidBody(5), COL_SHAPE, shapeColidesWith); globalObjCount++; btVector3 bottom_wall = btVector3(6.f, 6.f, 6.f); tempShape = new btBoxShape( bottom_wall); tempMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0, 0, -9.f))); tempMass = 100; tempInertia = btVector3(0.0f, 0.0f, 0.0f); objectsDataList.addObject(6, tempShape, tempMotionState, tempMass, tempInertia, 0, 1, .5f); dynamicsWorld->addRigidBody(objectsDataList.getRigidBody(6), COL_SHAPE, shapeColidesWith); globalObjCount++; btVector3 right_wall = btVector3(4.f, 4.f, 4.f); tempShape = new btBoxShape( right_wall); tempMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(-7, 0, 0.0f))); tempMass = 100; tempInertia = btVector3(0.0f, 0.0f, 0.0f); objectsDataList.addObject(7, tempShape, tempMotionState, tempMass, tempInertia, 0, 1, .5f); dynamicsWorld->addRigidBody(objectsDataList.getRigidBody(7), COL_SHAPE, shapeColidesWith); */ //Clean Up //tempShape = NULL; //delete objTriMesh; //objTriMesh = NULL; tempShape = NULL; tempMotionState = NULL; //--Load vertex shader and fragment shader from 2 text files ShaderLoader loader("vertexShader.txt", "fragmentShader.txt"); program = loader.LoadShader(); //Now we set the locations of the attributes and uniforms //this allows us to access them easily while rendering loc_position = glGetAttribLocation(program, const_cast<const char*>("v_position")); if(loc_position == -1) { std::cerr << "[F] POSITION NOT FOUND" << std::endl; return false; } loc_uv = glGetAttribLocation(program, const_cast<const char*>("v_uv")); if(loc_uv == -1) { std::cerr << "[F] V_UV NOT FOUND" << std::endl; return false; } loc_mvpmat = glGetUniformLocation(program, const_cast<const char*>("mvpMatrix")); if(loc_mvpmat == -1) { std::cerr << "[F] MVPMATRIX NOT FOUND" << std::endl; return false; } //--Init the view and projection matrices // if you will be having a moving camera the view matrix will need to more dynamic // ...Like you should update it before you render more dynamic // for this project having them static will be fine view = glm::lookAt( glm::vec3(.5, 7.0, 0), //Eye Position glm::vec3(.5, 0.0, 0.0), //Focus point glm::vec3(0.0, 0.0, 1.0)); //Positive Y is up projection = glm::perspective( 45.0f, //the FoV typically 90 degrees is good which is what this is set to float(w)/float(h), //Aspect Ratio, so Circles stay Circular 0.01f, //Distance to the near plane, normally a small value like this 100.0f); //Distance to the far plane, // load texture image Magick::InitializeMagick(""); Magick::Image image; Magick::Blob m_blob; try { // Read a file into image object if ( textureFileName != "") { image.read( textureFileName ); image.flip(); image.write(&m_blob, "RGBA"); } else { throw std::invalid_argument("No texture file found"); } } catch(exception& tmp) { cout << "Error while reading in texture image, texture file not found" << endl; } int imageWidth = image.columns(); int imageHeight = image.rows(); // setup texture glGenTextures(1, &aTexture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, aTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_blob.data()); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //enable depth testing glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); //and its done return true; }
GLUSboolean init(GLUSvoid) { GLUSshape background; GLUSshape torus; GLUStextfile vertexSource; GLUStextfile fragmentSource; GLfloat viewMatrix[16]; GLfloat lightDirection[3]; GLenum none[] = {GL_NONE}; lightDirection[0] = g_lightPosition[0]; lightDirection[1] = g_lightPosition[1]; lightDirection[2] = g_lightPosition[2]; glusVector3Normalizef(lightDirection); // glusLoadTextFile("../Example12_ES/shader/rendershadow.vert.glsl", &vertexSource); glusLoadTextFile("../Example12_ES/shader/rendershadow.frag.glsl", &fragmentSource); glusBuildProgramFromSource(&g_programShadow, (const GLUSchar**) &vertexSource.text, (const GLUSchar**) &fragmentSource.text); glusDestroyTextFile(&vertexSource); glusDestroyTextFile(&fragmentSource); // glusLoadTextFile("../Example12_ES/shader/useshadow.vert.glsl", &vertexSource); glusLoadTextFile("../Example12_ES/shader/useshadow.frag.glsl", &fragmentSource); glusBuildProgramFromSource(&g_program, (const GLUSchar**) &vertexSource.text, (const GLUSchar**) &fragmentSource.text); glusDestroyTextFile(&vertexSource); glusDestroyTextFile(&fragmentSource); // g_projectionMatrixShadowLocation = glGetUniformLocation(g_programShadow.program, "u_projectionMatrix"); g_modelViewMatrixShadowLocation = glGetUniformLocation(g_programShadow.program, "u_modelViewMatrix"); g_vertexShadowLocation = glGetAttribLocation(g_programShadow.program, "a_vertex"); // g_projectionMatrixLocation = glGetUniformLocation(g_program.program, "u_projectionMatrix"); g_viewMatrixLocation = glGetUniformLocation(g_program.program, "u_viewMatrix"); g_modelMatrixLocation = glGetUniformLocation(g_program.program, "u_modelMatrix"); g_normalMatrixLocation = glGetUniformLocation(g_program.program, "u_normalMatrix"); g_shadowMatrixLocation = glGetUniformLocation(g_program.program, "u_shadowMatrix"); g_shadowTextureLocation = glGetUniformLocation(g_program.program, "u_shadowTexture"); g_colorLocation = glGetUniformLocation(g_program.program, "u_shapeColor"); g_lightDirectionLocation = glGetUniformLocation(g_program.program, "u_lightDirection"); g_vertexLocation = glGetAttribLocation(g_program.program, "a_vertex"); g_normalLocation = glGetAttribLocation(g_program.program, "a_normal"); // glGenTextures(1, &g_shadowTexture); glBindTexture(GL_TEXTURE_2D, g_shadowTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, g_shadowTextureSize, g_shadowTextureSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS); glBindTexture(GL_TEXTURE_2D, 0); // glGenFramebuffers(1, &g_fbo); glBindFramebuffer(GL_FRAMEBUFFER, g_fbo); glDrawBuffers(1, none); glReadBuffer(GL_NONE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, g_shadowTexture, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { printf("GL_FRAMEBUFFER_COMPLETE error 0x%x", glCheckFramebufferStatus(GL_FRAMEBUFFER)); return GLUS_FALSE; } glClearDepthf(1.0f); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glBindFramebuffer(GL_FRAMEBUFFER, 0); // glusCreateTorusf(&torus, 0.5f, 1.0f, 32, 32); g_numberIndicesSphere = torus.numberIndices; glGenBuffers(1, &g_verticesVBO); glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO); glBufferData(GL_ARRAY_BUFFER, torus.numberVertices * 4 * sizeof(GLfloat), (GLfloat*) torus.vertices, GL_STATIC_DRAW); glGenBuffers(1, &g_normalsVBO); glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO); glBufferData(GL_ARRAY_BUFFER, torus.numberVertices * 3 * sizeof(GLfloat), (GLfloat*) torus.normals, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &g_indicesVBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, torus.numberIndices * sizeof(GLuint), (GLuint*) torus.indices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glusDestroyShapef(&torus); // glusCreatePlanef(&background, 10.0f); g_numberIndicesBackground = background.numberIndices; glGenBuffers(1, &g_verticesBackgroundVBO); glBindBuffer(GL_ARRAY_BUFFER, g_verticesBackgroundVBO); glBufferData(GL_ARRAY_BUFFER, background.numberVertices * 4 * sizeof(GLfloat), (GLfloat*) background.vertices, GL_STATIC_DRAW); glGenBuffers(1, &g_normalsBackgroundVBO); glBindBuffer(GL_ARRAY_BUFFER, g_normalsBackgroundVBO); glBufferData(GL_ARRAY_BUFFER, background.numberVertices * 3 * sizeof(GLfloat), (GLfloat*) background.normals, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &g_indicesBackgroundVBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesBackgroundVBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, background.numberIndices * sizeof(GLuint), (GLuint*) background.indices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glusDestroyShapef(&background); // glUseProgram(g_program.program); glusLookAtf(viewMatrix, g_cameraPosition[0], g_cameraPosition[1], g_cameraPosition[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); glusMatrix4x4MultiplyVector3f(lightDirection, viewMatrix, lightDirection); glUniform3fv(g_lightDirectionLocation, 1, lightDirection); glUniform1i(g_shadowTextureLocation, 0); // Torus glGenVertexArrays(1, &g_vao); glBindVertexArray(g_vao); glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO); glVertexAttribPointer(g_vertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_vertexLocation); glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO); glVertexAttribPointer(g_normalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_normalLocation); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO); // Plane glGenVertexArrays(1, &g_vaoBackground); glBindVertexArray(g_vaoBackground); glBindBuffer(GL_ARRAY_BUFFER, g_verticesBackgroundVBO); glVertexAttribPointer(g_vertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_vertexLocation); glBindBuffer(GL_ARRAY_BUFFER, g_normalsBackgroundVBO); glVertexAttribPointer(g_normalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_normalLocation); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesBackgroundVBO); // glUseProgram(g_programShadow.program); // Torus glGenVertexArrays(1, &g_vaoShadow); glBindVertexArray(g_vaoShadow); glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO); glVertexAttribPointer(g_vertexShadowLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_vertexShadowLocation); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO); // Plane glGenVertexArrays(1, &g_vaoShadowBackground); glBindVertexArray(g_vaoShadowBackground); glBindBuffer(GL_ARRAY_BUFFER, g_verticesBackgroundVBO); glVertexAttribPointer(g_vertexShadowLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_vertexShadowLocation); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesBackgroundVBO); // glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepthf(1.0f); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); // Needed when rendering the shadow map. This will avoid artifacts. glPolygonOffset(1.0f, 0.0f); return GLUS_TRUE; }
void init() { // Vertices of a square double ext = 1.0; vec4 points[NumPoints] = { vec4( -ext, -ext, 0, 1.0 ), //v1 vec4( ext, -ext, 0, 1.0 ), //v2 vec4( -ext, ext, 0, 1.0 ), //v3 vec4( -ext, ext, 0, 1.0 ), //v3 vec4( ext, -ext, 0, 1.0 ), //v2 vec4( ext, ext, 0, 1.0 ) //v4 }; // Texture coordinates vec2 tex_coords[NumPoints] = { vec2( 0.0, 0.0 ), vec2( 1.0, 0.0 ), vec2( 0.0, 1.0 ), vec2( 0.0, 1.0 ), vec2( 1.0, 0.0 ), vec2( 1.0, 1.0 ) }; // Initialize texture objects GLuint texture; glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, WIN_WIDTH, WIN_HEIGHT, 0, GL_RGB, GL_FLOAT, frame ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glActiveTexture( GL_TEXTURE0 ); // Create and initialize a buffer object GLuint buffer; glGenBuffers( 1, &buffer ); glBindBuffer( GL_ARRAY_BUFFER, buffer ); glBufferData( GL_ARRAY_BUFFER, sizeof(points) + sizeof(tex_coords), NULL, GL_STATIC_DRAW ); GLintptr offset = 0; glBufferSubData( GL_ARRAY_BUFFER, offset, sizeof(points), points ); offset += sizeof(points); glBufferSubData( GL_ARRAY_BUFFER, offset, sizeof(tex_coords), tex_coords ); // Load shaders and use the resulting shader program GLuint program = InitShader( "vshader.glsl", "fshader.glsl" ); glUseProgram( program ); // set up vertex arrays offset = 0; GLuint vPosition = glGetAttribLocation( program, "vPosition" ); glEnableVertexAttribArray( vPosition ); glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(offset) ); offset += sizeof(points); GLuint vTexCoord = glGetAttribLocation( program, "vTexCoord" ); glEnableVertexAttribArray( vTexCoord ); glVertexAttribPointer( vTexCoord, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(offset) ); glUniform1i( glGetUniformLocation(program, "texture"), 0 ); glClearColor( 1.0, 1.0, 1.0, 1.0 ); }
bool CFXMosaic::DoFrame(CDemo* pDemo, float fEffectTime, float fDemoTime) { assert(pDemo); if(!m_pResTexture) { FXRuntimeError("Texture resource not found"); return false; } UtilGL::Texturing::CTexture2D* pTexture = const_cast<UtilGL::Texturing::CTexture2D*>(((CResourceTexture2D*)m_pResTexture)->GetTexture2D()); if(!pTexture) { FXRuntimeError("WARNING: Texture not available"); return false; } if(m_vecTiles.size() < 1) { FXRuntimeError("WARNING: No tiles available"); return false; } CVarFloat::CValueFloat valuePosX; CVarFloat::CValueFloat valuePosY; CVarFloat::CValueFloat valueWidth; CVarFloat::CValueFloat valueHeight; CVarFloat::CValueFloat valueScale; CVarFloat::CValueFloat valueAlpha; CVarFloat::CValueFloat valueAngle; CVarCombo::CValueCombo valueBlendMode; CVarCombo::CValueCombo valueFiltering; CVarInt::CValueInt valueTilesX; CVarInt::CValueInt valueTilesY; CVarInt::CValueInt valueTileSourceWidth; CVarInt::CValueInt valueTileSourceHeight; CVarFloat::CValueFloat valueChangeFrequency; CVarFloat::CValueFloat valueChangeFreqVariation; EvaluateVar("X Position", fEffectTime, &valuePosX); EvaluateVar("Y Position", fEffectTime, &valuePosY); EvaluateVar("Width", fEffectTime, &valueWidth); EvaluateVar("Height", fEffectTime, &valueHeight); EvaluateVar("Scale", fEffectTime, &valueScale); EvaluateVar("Alpha", fEffectTime, &valueAlpha); EvaluateVar("Angle", fEffectTime, &valueAngle); EvaluateVar("Blend Mode", fEffectTime, &valueBlendMode); EvaluateVar("Filtering", fEffectTime, &valueFiltering); EvaluateVar("Tiles X", fEffectTime, &valueTilesX); EvaluateVar("Tiles Y", fEffectTime, &valueTilesY); EvaluateVar("Tile Source Width", fEffectTime, &valueTileSourceWidth); EvaluateVar("Tile Source Height", fEffectTime, &valueTileSourceHeight); EvaluateVar("Change Frequency", fEffectTime, &valueChangeFrequency); EvaluateVar("Change Freq Variation", fEffectTime, &valueChangeFreqVariation); // Change filter mode GLint minFilter, magFilter; GLfloat fMaxAnisotropy; UtilGL::States::Set(UtilGL::States::TEXTURE2D, UtilGL::States::ENABLED); pTexture->SetActive(); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, &minFilter); glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, &magFilter); if(UtilGL::Extensions::GetAvailableExtensions()->EXT_texture_filter_anisotropic) { glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fMaxAnisotropy); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); } if(valueFiltering.GetValue() == "Yes") { // If it's point filtering, change it to linear, otherwise leave it as it is if(minFilter == GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if(magFilter == GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } CVarFloat* pVarAngle = reinterpret_cast<CVarFloat*>(GetVar("Angle")); assert(pVarAngle); float fAlpha = valueAlpha.GetValue() > 1.0f ? 1.0f : valueAlpha.GetValue(); if(fAlpha < ALMOST_ZERO) { return true; } CVector4 v4Color(1.0f, 1.0f, 1.0f, fAlpha); UtilGL::States::SetColor(v4Color); float fAngle = valueAngle.GetValue(); if(IS_ZERO(fAngle) && !pVarAngle->IsConstant()) { // Avoid aspect ratio problem (see UtilGL::Rendering::DrawRect()) fAngle = fAngle < 0.0f ? fAngle - (ALMOST_ZERO * 2.0f) : fAngle + (ALMOST_ZERO * 2.0f); } int nSrcBlend = UtilGL::States::BLEND_SRCALPHA; int nDstBlend = UtilGL::States::BLEND_INVSRCALPHA; if(valueBlendMode.GetValue() == "Add") nDstBlend = UtilGL::States::BLEND_ONE; else if(valueBlendMode.GetValue() == "Mult") nDstBlend = UtilGL::States::BLEND_INVSRCALPHA; else if(valueBlendMode.GetValue() == "Color Mult") { nSrcBlend = UtilGL::States::BLEND_DSTCOLOR; nDstBlend = UtilGL::States::BLEND_ZERO; } if(ARE_EQUAL(fAlpha, 1.0f) && valueBlendMode.GetValue() == "Mult" && !pTexture->HasAlpha()) { nSrcBlend = UtilGL::States::BLEND_ONE; nDstBlend = UtilGL::States::BLEND_ZERO; } if(!((nSrcBlend == UtilGL::States::BLEND_ONE && nDstBlend == UtilGL::States::BLEND_ZERO) || (nSrcBlend == UtilGL::States::BLEND_ZERO && nDstBlend == UtilGL::States::BLEND_ONE))) { UtilGL::States::Set(UtilGL::States::BLENDING, UtilGL::States::ENABLED); UtilGL::States::Set(UtilGL::States::SRCBLEND, nSrcBlend); UtilGL::States::Set(UtilGL::States::DSTBLEND, nDstBlend); } else { UtilGL::States::Set(UtilGL::States::BLENDING, UtilGL::States::DISABLED); } UtilGL::States::Set(UtilGL::States::LIGHTING, UtilGL::States::DISABLED); UtilGL::States::Set(UtilGL::States::ZBUFFER, UtilGL::States::DISABLED); UtilGL::Transforming::ClearMatrix(UtilGL::Transforming::MATRIX_WORLD); UtilGL::Transforming::ClearMatrix(UtilGL::Transforming::MATRIX_VIEW); UtilGL::Transforming::ClearMatrix(UtilGL::Transforming::MATRIX_PROJECTION); glMatrixMode(GL_PROJECTION); glOrtho(0, pTexture->GetWidth(), pTexture->GetHeight(), 0, 0.0f, 10.0f); // Update *********** int nImgTilesX = pTexture && valueTileSourceWidth.GetValue() > 0 ? pTexture->GetWidth() / valueTileSourceWidth.GetValue() : 1; int nImgTilesY = pTexture && valueTileSourceHeight.GetValue() > 0 ? pTexture->GetHeight() / valueTileSourceHeight.GetValue() : 1; float fChangePeriod = IS_ZERO(valueChangeFrequency.GetValue()) ? FLOAT_MAX : 1.0f / valueChangeFrequency.GetValue(); if(fChangePeriod < 0.0001f) fChangePeriod = 0.0001f; while(MYFABSF(m_fLastUpdate - fEffectTime) > fChangePeriod) { int nRandTile = rand() % m_vecTiles.size(); m_vecTiles[nRandTile].nImgTileX = rand() % nImgTilesX; m_vecTiles[nRandTile].nImgTileY = rand() % nImgTilesY; if(fEffectTime < m_fLastUpdate) { m_fLastUpdate -= fChangePeriod; } else { m_fLastUpdate += fChangePeriod; } } // Render *********** VECTILES::iterator it; float fUTileWidth = (float)valueTileSourceWidth.GetValue() / (float)pTexture->GetWidth(); float fVTileHeight = (float)valueTileSourceHeight.GetValue() / (float)pTexture->GetHeight(); int nTilesX = valueTilesX.GetValue() < 1 ? 1 : valueTilesX.GetValue(); int nTilesY = valueTilesY.GetValue() < 1 ? 1 : valueTilesY.GetValue(); for(it = m_vecTiles.begin(); it < m_vecTiles.end(); ++it) { STile tile = *it; float fTileWidth = pTexture->GetWidth() / (float)nTilesX; float fTileHeight = pTexture->GetHeight() / (float)nTilesY; float fPosX = ((valuePosX.GetValue() - 0.5f) * pTexture->GetWidth()) + (fTileWidth * tile.nX); float fPosY = ((valuePosY.GetValue() - 0.5f) * pTexture->GetHeight()) + (fTileHeight * tile.nY); float fScaleX = valueWidth.GetValue() * valueScale.GetValue(); float fScaleY = valueHeight.GetValue() * valueScale.GetValue(); float fU = tile.nImgTileX * fUTileWidth; float fV = 1.0f - (tile.nImgTileY * fVTileHeight); float fU2 = fU + fUTileWidth; float fV2 = fV - fVTileHeight; CVector3 v3Center(pTexture->GetWidth() * 0.5f, pTexture->GetHeight() * 0.5f, -5.0f); CMatrix worldMtx; worldMtx.SetIdentity(); worldMtx.Translate(fPosX, fPosY, 0.0f); worldMtx.Translate(-v3Center.X(), -v3Center.Y(), 0.0f); worldMtx.Scale (fScaleX, fScaleY, 1.0f); worldMtx.RotateZ (fAngle); worldMtx.Translate(+v3Center.X(), +v3Center.Y(), 0.0f); UtilGL::Transforming::SetMatrix(UtilGL::Transforming::MATRIX_WORLD, worldMtx); glBegin(GL_QUADS); glTexCoord2f(fU, fV); glVertex3f(0.0f, 0.0f, -5.0f); glTexCoord2f(fU, fV2); glVertex3f(0.0f, fTileHeight, -5.0f); glTexCoord2f(fU2, fV2); glVertex3f(fTileWidth, fTileHeight, -5.0f); glTexCoord2f(fU2, fV); glVertex3f(fTileWidth, 0.0f, -5.0f); glEnd(); } glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, pDemo->GetAspect(), 1.0f, 1000.0f); // Restore filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter); UtilGL::States::Set(UtilGL::States::TEXTURE2D, UtilGL::States::DISABLED); if(UtilGL::Extensions::GetAvailableExtensions()->EXT_texture_filter_anisotropic) { glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fMaxAnisotropy); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fMaxAnisotropy); } UtilGL::States::Set(UtilGL::States::TEXTURE2D, UtilGL::States::DISABLED); UtilGL::States::Set(UtilGL::States::BLENDING, UtilGL::States::DISABLED); UtilGL::States::Set(UtilGL::States::ZBUFFER, UtilGL::States::ENABLED); return true; }
Scene::Scene(Window& window) : OGLRenderer(window) { //used as friend class AssetsManager::InitializeMeshes(); /*m_DebugShader = new Shader(SHADERDIR"debugVertex.glsl", SHADERDIR"debugFragment.glsl"); if (!m_DebugShader->LinkProgram()){ return; } m_DefaultLightShader = new Shader(SHADERDIR"TechVertex.glsl", SHADERDIR"TechLightFragment.glsl"); if (!m_DefaultLightShader->LinkProgram()){ return; } m_DefaultShadowShader = new Shader(SHADERDIR"TechVertex.glsl", SHADERDIR"TechShadowFragment.glsl"); if (!m_DefaultShadowShader->LinkProgram()){ return; } m_ShadowVolumeShader = new Shader(SHADERDIR"TechVertex.glsl", SHADERDIR"PassThroughFragment.glsl", SHADERDIR"ShadowVolumeGeometry.glsl"); if (!m_ShadowVolumeShader->LinkProgram()){ return; }*/ SceneShader = new Shader(SHADERDIR"TardisVertex.glsl", SHADERDIR"TardisFragment.glsl"); if (!SceneShader->LinkProgram()){ return; } ShadowShader = new Shader(SHADERDIR"shadowVert.glsl", SHADERDIR"shadowFrag.glsl"); if (!ShadowShader->LinkProgram()){ return; } ////******************************* ////** CUBE MAP ** ////******************************* ////for sky box m_skyboxShader = new Shader(SHADERDIR"skyboxVertex.glsl", SHADERDIR"skyboxFragment.glsl"); if (!m_skyboxShader->LinkProgram()){ return; } cubeMap = SOIL_load_OGL_cubemap( TEXTUREDIR"skyBox/sky_pos_z.jpg", TEXTUREDIR"skyBox/sky_neg_z.jpg", TEXTUREDIR"skyBox/sky_pos_y.jpg", TEXTUREDIR"skyBox/sky_neg_y.jpg", TEXTUREDIR"skyBox/sky_neg_x.jpg", TEXTUREDIR"skyBox/sky_pos_x.jpg", SOIL_LOAD_RGB, SOIL_CREATE_NEW_ID, 0); if (!cubeMap) { return; } m_ParticleShader = new Shader(SHADERDIR"ParticleVertex.glsl", SHADERDIR"ParticleFragment.glsl", SHADERDIR"ParticleGeometry.glsl"); if (!m_ParticleShader->LinkProgram()) { return; } m_RootParticleList = new ParticleEmitter(); m_Camera = new Camera(); m_RootGameObject = new GameObject(); //root is created here m_RootGameObject->m_Scene = this; m_AmbientColour = Vector3(0.2f, 0.2f, 0.2f); m_InvLightDirection = Vector3(0.5f, 1.0f, -0.8f); m_SpecularIntensity = 128.0f; m_InvLightDirection.Normalise(); m_ScreenDTex = NULL; m_ScreenCTex = NULL; m_ScreenFBO = NULL; BuildScreenFBO(); clearcolor = Vector4(0.6f, 0.6f, 0.6f, 1.f); glClearColor(clearcolor.x, clearcolor.y, clearcolor.z, clearcolor.w); NCLDebug::LoadShaders(); init = true; lightList.push_back(Light(Vector3(0, 175, 0),//position Vector4(1, 1, 1, 1), //light color 600.0f //light radius , 2.0f // brightness , Vector3(1, 1, 1) )); lightList.push_back(Light(Vector3(0, 1.5f, 0),//position Vector4(1, 1, 1, 1), //light color 1.0f //light radius , 50.0f // brightness , Vector3(1, 1, 1) )); glGenTextures(1, &shadowTex); glBindTexture(GL_TEXTURE_2D, shadowTex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOWSIZE, SHADOWSIZE, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); glBindTexture(GL_TEXTURE_2D, 0); // create shadow FBO and bind depth texture glGenFramebuffers(1, &shadowFBO); glBindFramebuffer(GL_FRAMEBUFFER, shadowFBO); //for (int i = 0; i < 6; i++) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowTex, 0); glDrawBuffer(GL_NONE); //} glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_DEPTH_TEST); }
void QGLFramebufferObjectPrivate::init(QGLFramebufferObject *q, const QSize &sz, QGLFramebufferObject::Attachment attachment, GLenum texture_target, GLenum internal_format, GLint samples) { QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext()); fbo_guard.setContext(ctx); bool ext_detected = (QGLExtensions::glExtensions() & QGLExtensions::FramebufferObject); if (!ext_detected || (ext_detected && !qt_resolve_framebufferobject_extensions(ctx))) return; size = sz; target = texture_target; // texture dimensions QT_RESET_GLERROR(); // reset error state GLuint fbo = 0; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER_EXT, fbo); fbo_guard.setId(fbo); glDevice.setFBO(q, attachment); QT_CHECK_GLERROR(); // init texture if (samples == 0) { glGenTextures(1, &texture); glBindTexture(target, texture); glTexImage2D(target, 0, internal_format, size.width(), size.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); #ifndef QT_OPENGL_ES glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #else glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #endif glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, texture, 0); QT_CHECK_GLERROR(); valid = checkFramebufferStatus(); glBindTexture(target, 0); color_buffer = 0; } else { GLint maxSamples; glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); samples = qBound(0, int(samples), int(maxSamples)); glGenRenderbuffers(1, &color_buffer); glBindRenderbuffer(GL_RENDERBUFFER_EXT, color_buffer); if (glRenderbufferStorageMultisampleEXT && samples > 0) { glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, internal_format, size.width(), size.height()); } else { samples = 0; glRenderbufferStorage(GL_RENDERBUFFER_EXT, internal_format, size.width(), size.height()); } glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, color_buffer); QT_CHECK_GLERROR(); valid = checkFramebufferStatus(); if (valid) glGetRenderbufferParameteriv(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_SAMPLES_EXT, &samples); } // In practice, a combined depth-stencil buffer is supported by all desktop platforms, while a // separate stencil buffer is not. On embedded devices however, a combined depth-stencil buffer // might not be supported while separate buffers are, according to QTBUG-12861. if (attachment == QGLFramebufferObject::CombinedDepthStencil && (QGLExtensions::glExtensions() & QGLExtensions::PackedDepthStencil)) { // depth and stencil buffer needs another extension glGenRenderbuffers(1, &depth_buffer); Q_ASSERT(!glIsRenderbuffer(depth_buffer)); glBindRenderbuffer(GL_RENDERBUFFER_EXT, depth_buffer); Q_ASSERT(glIsRenderbuffer(depth_buffer)); if (samples != 0 && glRenderbufferStorageMultisampleEXT) glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH24_STENCIL8_EXT, size.width(), size.height()); else glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, size.width(), size.height()); stencil_buffer = depth_buffer; glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_buffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, stencil_buffer); valid = checkFramebufferStatus(); if (!valid) { glDeleteRenderbuffers(1, &depth_buffer); stencil_buffer = depth_buffer = 0; } } if (depth_buffer == 0 && (attachment == QGLFramebufferObject::CombinedDepthStencil || (attachment == QGLFramebufferObject::Depth))) { glGenRenderbuffers(1, &depth_buffer); Q_ASSERT(!glIsRenderbuffer(depth_buffer)); glBindRenderbuffer(GL_RENDERBUFFER_EXT, depth_buffer); Q_ASSERT(glIsRenderbuffer(depth_buffer)); if (samples != 0 && glRenderbufferStorageMultisampleEXT) { #ifdef QT_OPENGL_ES if (QGLExtensions::glExtensions() & QGLExtensions::Depth24) { glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH_COMPONENT24_OES, size.width(), size.height()); } else { glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH_COMPONENT16, size.width(), size.height()); } #else glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH_COMPONENT, size.width(), size.height()); #endif } else { #ifdef QT_OPENGL_ES if (QGLExtensions::glExtensions() & QGLExtensions::Depth24) { glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24_OES, size.width(), size.height()); } else { glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, size.width(), size.height()); } #else glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, size.width(), size.height()); #endif } glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_buffer); valid = checkFramebufferStatus(); if (!valid) { glDeleteRenderbuffers(1, &depth_buffer); depth_buffer = 0; } } if (stencil_buffer == 0 && (attachment == QGLFramebufferObject::CombinedDepthStencil)) { glGenRenderbuffers(1, &stencil_buffer); Q_ASSERT(!glIsRenderbuffer(stencil_buffer)); glBindRenderbuffer(GL_RENDERBUFFER_EXT, stencil_buffer); Q_ASSERT(glIsRenderbuffer(stencil_buffer)); if (samples != 0 && glRenderbufferStorageMultisampleEXT) { #ifdef QT_OPENGL_ES glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_STENCIL_INDEX8_EXT, size.width(), size.height()); #else glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_STENCIL_INDEX, size.width(), size.height()); #endif } else { #ifdef QT_OPENGL_ES glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX8_EXT, size.width(), size.height()); #else glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX, size.width(), size.height()); #endif } glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, stencil_buffer); valid = checkFramebufferStatus(); if (!valid) { glDeleteRenderbuffers(1, &stencil_buffer); stencil_buffer = 0; } } // The FBO might have become valid after removing the depth or stencil buffer. valid = checkFramebufferStatus(); if (depth_buffer && stencil_buffer) { fbo_attachment = QGLFramebufferObject::CombinedDepthStencil; } else if (depth_buffer) { fbo_attachment = QGLFramebufferObject::Depth; } else { fbo_attachment = QGLFramebufferObject::NoAttachment; } glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); if (!valid) { if (color_buffer) glDeleteRenderbuffers(1, &color_buffer); else glDeleteTextures(1, &texture); if (depth_buffer) glDeleteRenderbuffers(1, &depth_buffer); if (stencil_buffer && depth_buffer != stencil_buffer) glDeleteRenderbuffers(1, &stencil_buffer); glDeleteFramebuffers(1, &fbo); fbo_guard.setId(0); } QT_CHECK_GLERROR(); format.setTextureTarget(target); format.setSamples(int(samples)); format.setAttachment(fbo_attachment); format.setInternalTextureFormat(internal_format); }
/* Load BMF file format, function return bitmap font descriptor */ int glfLoadBMFFont(char *FName) { FILE *f; char Header[4]; char FontName[97]; int i, flag; int LEndian; float tx, ty, tw, th; unsigned char temp, *tp; unsigned *texture; /* Texture image */ unsigned *mask; /* Mask texture */ int twidth, theight, tcomp; /* Image parameters */ float *temp_width; LEndian = LittleEndian(); f = fopen(FName, "rb"); if (f == NULL) return GLF_ERROR; /* Error opening file */ /* Get header */ fread(Header, 1, 3, f); Header[3] = 0; if (strcmp(Header, "BMF")) return GLF_ERROR; /* Not BMF format */ /* Get font name */ fread(FontName, 1, 96, f); FontName[96] = 0; /* Allocate space for temp widths */ temp_width = (float *)malloc(sizeof(float)*256); /* Read all 256 symbols information */ for (i=0; i<256; i++) { fread(&tx, 4, 1, f); fread(&ty, 4, 1, f); fread(&tw, 4, 1, f); fread(&th, 4, 1, f); if (!LEndian) { tp = (unsigned char *)&tx; temp = tp[0]; tp[0] = tp[3]; tp[3] = temp; temp = tp[1]; tp[1] = tp[2]; tp[2] = temp; tp = (unsigned char *)&ty; temp = tp[0]; tp[0] = tp[3]; tp[3] = temp; temp = tp[1]; tp[1] = tp[2]; tp[2] = temp; tp = (unsigned char *)&tw; temp = tp[0]; tp[0] = tp[3]; tp[3] = temp; temp = tp[1]; tp[1] = tp[2]; tp[2] = temp; tp = (unsigned char *)&th; temp = tp[0]; tp[0] = tp[3]; tp[3] = temp; temp = tp[1]; tp[1] = tp[2]; tp[2] = temp; } Symbols[i].x = tx; Symbols[i].y = ty; Symbols[i].width = tw; Symbols[i].height = th; temp_width[i] = tw; } /* Read texture image from file and build texture */ texture = read_texture(f, &twidth, &theight, &tcomp); /* Generate mask texture */ mask = texture_to_mask(texture, twidth, theight); /* Find unused font descriptor */ flag = 0; for (i=0; i<MAX_FONTS; i++) if (bmf_in_use[i] == 0) { /* Initialize this font */ bmf_in_use[i] = 1; bmf_curfont = i; flag = 1; break; } if (!flag) /* Not enought space for new texture */ { fclose(f); free(texture); free(mask); free(temp_width); return -1; } m_widths[bmf_curfont].width = temp_width; /* Generating textures for font and mask */ glGenTextures(1, &bmf_texture[bmf_curfont]); glGenTextures(1, &bmf_mask[bmf_curfont]); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); /* Build font texture */ glBindTexture(GL_TEXTURE_2D, bmf_texture[bmf_curfont]); glTexImage2D(GL_TEXTURE_2D, 0, 3, twidth, theight, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture); /* Linear filtering for better quality */ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); /* Build mask texture */ glBindTexture(GL_TEXTURE_2D, bmf_mask[bmf_curfont]); glTexImage2D(GL_TEXTURE_2D, 0, 3, twidth, theight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mask); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); free(texture); free(mask); fclose(f); /* Now build list for each symbol */ list_base[bmf_curfont] = glGenLists(256); for (i=0; i<256; i++) { glNewList(list_base[bmf_curfont]+i, GL_COMPILE); glBegin(GL_QUADS); glTexCoord2f(Symbols[i].x, Symbols[i].y); glVertex2f(0, 0); glTexCoord2f(Symbols[i].x+Symbols[i].width, Symbols[i].y); glVertex2f(Symbols[i].width, 0); glTexCoord2f(Symbols[i].x+Symbols[i].width, Symbols[i].y+Symbols[i].height); glVertex2f(Symbols[i].width, Symbols[i].height); glTexCoord2f(Symbols[i].x, Symbols[i].y+Symbols[i].height); glVertex2f(0, Symbols[i].height); glEnd(); glTranslatef(Symbols[i].width+sym_space, 0, 0); glEndList(); if (Symbols[i].height > m_max_height[bmf_curfont]) m_max_height[bmf_curfont] = Symbols[i].height; } return bmf_curfont; }
// Do an actual card upload (well, at least tell the OpenGL driver you'd like one when it // gets a chance) of a texture. Called from the Render_* functions when they require // use of a texture that is marked for updating (THANDLE_UPDATE) void THandle_Update(geRDriver_THandle *THandle) { if(THandle->PixelFormat.Flags & RDRIVER_PF_2D) { if(THandle->PixelFormat.PixelFormat == GE_PIXELFORMAT_24BIT_RGB) { if(THandle->Width <= maxTextureSize && THandle->Height <= maxTextureSize) { GLubyte *dest; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_PRIORITY, 0.5f); dest = (GLubyte*)malloc(THandle->PaddedWidth * THandle->PaddedHeight * 4); CkBlit24_32(dest, THandle->PaddedWidth, THandle->PaddedHeight, THandle->Data[0], THandle->Width, THandle->Height); glTexImage2D(GL_TEXTURE_2D, 0, 4, THandle->PaddedWidth, THandle->PaddedHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, dest); free(dest); } else { if(THandle->Data[1] != NULL) { free(THandle->Data[1]); } THandle->Data[1] = (GLubyte*)malloc(THandle->Width * THandle->Height * 4); CkBlit24_32(THandle->Data[1], THandle->Width, THandle->Height, THandle->Data[0], THandle->Width, THandle->Height); } } } else { #ifdef USE_LINEAR_INTERPOLATION #ifdef TRILINEAR_INTERPOLATION glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); #endif #else #ifdef TRILINEAR_INTERPOLATION glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); #else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); #endif #endif if(THandle->PixelFormat.PixelFormat == GE_PIXELFORMAT_32BIT_ABGR) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_PRIORITY, 1.0f); gluBuild2DMipmaps(GL_TEXTURE_2D, 4, THandle->Width, THandle->Height, GL_RGBA, GL_UNSIGNED_BYTE, THandle->Data[0]); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_PRIORITY, 0.0f); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, THandle->Width, THandle->Height, GL_RGB, GL_UNSIGNED_BYTE, THandle->Data[0]); } if (bUseAnisotropicFiltering) { glTexParameterf(GL_TEXTURE_2D, GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, fMaxAnisotropy); } } THandle->Flags &= ~THANDLE_UPDATE; }
void Obj::render(glm::vec3 pos, float angle) { for(int q = 0; q < gpuDataList.size(); q++) { ObjGPUData* gpuData = gpuDataList[q]; Shader* requiredShader = shaderList[q]; if(currentShader != requiredShader) { glUseProgram(requiredShader->shaderProgram); currentShader = requiredShader; } /*** Bind VAO associated w/ object ***/ glBindVertexArray(gpuData->vertexArrayObj); /*** Iterate through all of the object pieces and render ***/ for(int i = 0; i < gpuData->materialIndices.size()/2; i++) { unsigned int first = (gpuData->materialIndices)[i*2]; unsigned int last; if((2*i + 2) > (gpuData->materialIndices.size() - 1)) last = gpuData->fList.size(); else last = (gpuData->materialIndices)[i*2 + 2]; unsigned int totalElements = last - first; std::map<std::string, GLuint>::iterator uniformID; std::map<std::string, GLuint>::iterator mapEnd = currentShader->uniformIDMap.end(); /*** Bind the textures required by the object piece ***/ uniformID = currentShader->uniformIDMap.find("Texture"); if(uniformID != mapEnd) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, (gpuData->materials)[(gpuData->materialIndices)[i*2 + 1]].texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 11); glUniform1i(currentShader->uniformIDMap.find("Texture")->second, 0); } uniformID = currentShader->uniformIDMap.find("Bump"); if(uniformID != mapEnd) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, (gpuData->materials)[(gpuData->materialIndices)[i*2 + 1]].bump); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 11); glUniform1i(currentShader->uniformIDMap.find("Bump")->second, 1); } /*** Calculate transformations used in rendering the object piece and pass to shaders ***/ glm::mat4 modelMatNoTranslate; glm::mat4 modelMat; if(transformOverrides){ modelMatNoTranslate = shearOverrideList[q] * glm::rotate(glm::mat4(1.0f), angle + rotationOverrideList[q], glm::vec3(0, 0, 1)) * glm::scale(glm::mat4(1.0f), modelScale) * gpuData->rotation * gpuData->unitScale; modelMat = glm::translate(glm::mat4(1.0f), pos + translationOverrideList[q]) * modelMatNoTranslate; } else { modelMatNoTranslate = glm::rotate(glm::mat4(1.0f), angle, glm::vec3(0, 0, 1)) * glm::scale(glm::mat4(1.0f), modelScale) * gpuData->rotation * gpuData->unitScale; modelMat = glm::translate(glm::mat4(1.0f), pos) * modelMatNoTranslate; } glm::mat4 modelViewMat = matView*modelMat; glm::mat3 modelView3x3 = glm::mat3(modelViewMat); glm::mat4 MVP = matProjection*modelViewMat; glm::mat3 normalMat = glm::transpose(glm::inverse(glm::mat3(modelViewMat))); glm::vec4 primaryLightPos_ViewSpace = matView * primaryLightPos; uniformID = currentShader->uniformIDMap.find("parallax"); if(uniformID != mapEnd) glUniform1i(uniformID->second, gpuData->parallax); uniformID = currentShader->uniformIDMap.find("texturePlane"); if(uniformID != mapEnd) glUniform1i(uniformID->second, gpuData->texturePlane); uniformID = currentShader->uniformIDMap.find("MVP"); if(uniformID != mapEnd) glUniformMatrix4fv(uniformID->second, 1, GL_FALSE, &MVP[0][0]); uniformID = currentShader->uniformIDMap.find("ModelViewMatrix"); if(uniformID != mapEnd) glUniformMatrix4fv(uniformID->second, 1, GL_FALSE, &modelViewMat[0][0]); uniformID = currentShader->uniformIDMap.find("ModelView3x3"); if(uniformID != mapEnd) glUniformMatrix3fv(uniformID->second, 1, GL_FALSE, &modelView3x3[0][0]); uniformID = currentShader->uniformIDMap.find("ModelMatrix"); if(uniformID != mapEnd) glUniformMatrix4fv(uniformID->second, 1, GL_FALSE, &modelMat[0][0]); uniformID = currentShader->uniformIDMap.find("ModelMatrixNoTranslate"); if(uniformID != mapEnd) glUniformMatrix4fv(uniformID->second, 1, GL_FALSE, &modelMatNoTranslate[0][0]); uniformID = currentShader->uniformIDMap.find("NormalMatrix"); if(uniformID != mapEnd) glUniformMatrix3fv(uniformID->second, 1, GL_FALSE, &normalMat[0][0]); uniformID = currentShader->uniformIDMap.find("ProjectionMatrix"); if(uniformID != mapEnd) glUniformMatrix4fv(uniformID->second, 1, GL_FALSE, &matProjection[0][0]); uniformID = currentShader->uniformIDMap.find("Material.Ka"); if(uniformID != mapEnd) glUniform3fv(uniformID->second, 1, &((gpuData->materials)[(gpuData->materialIndices)[i*2 + 1]].Ka)[0]); uniformID = currentShader->uniformIDMap.find("Material.Kd"); if(uniformID != mapEnd) glUniform3fv(uniformID->second, 1, &((gpuData->materials)[(gpuData->materialIndices)[i*2 + 1]].Kd)[0]); uniformID = currentShader->uniformIDMap.find("Material.Ks"); if(uniformID != mapEnd) glUniform3fv(uniformID->second, 1, &((gpuData->materials)[(gpuData->materialIndices)[i*2 + 1]].Ks)[0]); uniformID = currentShader->uniformIDMap.find("Material.shine"); if(uniformID != mapEnd) glUniform1f(uniformID->second, ((gpuData->materials)[(gpuData->materialIndices)[i*2 + 1]].shine)); uniformID = currentShader->uniformIDMap.find("Light.Position"); if(uniformID != mapEnd) glUniform4fv(uniformID->second, 1, &primaryLightPos_ViewSpace[0]); // glUniform4fv(uniformID->second, 1, &primaryLightPos[0]); uniformID = currentShader->uniformIDMap.find("Light.La"); if(uniformID != mapEnd) glUniform3fv(uniformID->second, 1, &primaryLightLa[0]); uniformID = currentShader->uniformIDMap.find("Light.Ld"); if(uniformID != mapEnd) glUniform3fv(uniformID->second, 1, &primaryLightLd[0]); uniformID = currentShader->uniformIDMap.find("Light.Ls"); if(uniformID != mapEnd) glUniform3fv(uniformID->second, 1, &primaryLightLs[0]); /*** Render the object piece ***/ glDrawElements(GL_TRIANGLES, totalElements, GL_UNSIGNED_INT, (void*)(first * sizeof(GLuint))); } } }
void subCompute(TRasterFxPort &m_input, TTile &tile, double frame, const TRenderSettings &ri, TPointD p00, TPointD p01, TPointD p11, TPointD p10, int details, bool wireframe, TDimension m_offScreenSize, bool isCast) { TPixel32 bgColor; TRectD outBBox, inBBox; outBBox = inBBox = TRectD(tile.m_pos, TDimensionD(tile.getRaster()->getLx(), tile.getRaster()->getLy())); m_input->getBBox(frame, inBBox, ri); if (inBBox == TConsts::infiniteRectD) // e' uno zerario inBBox = outBBox; int inBBoxLx = (int)inBBox.getLx() / ri.m_shrinkX; int inBBoxLy = (int)inBBox.getLy() / ri.m_shrinkY; if (inBBox.isEmpty()) return; if (p00 == p01 && p00 == p10 && p00 == p11 && !isCast) // significa che non c'e' deformazione { m_input->compute(tile, frame, ri); return; } TRaster32P rasIn; TPointD rasInPos; if (!wireframe) { if (ri.m_bpp == 64 || ri.m_bpp == 48) { TRaster64P aux = TRaster64P(inBBoxLx, inBBoxLy); rasInPos = TPointD(inBBox.x0 / ri.m_shrinkX, inBBox.y0 / ri.m_shrinkY); TTile tmp(aux, rasInPos); m_input->compute(tmp, frame, ri); rasIn = TRaster32P(inBBoxLx, inBBoxLy); TRop::convert(rasIn, aux); } else { rasInPos = TPointD(inBBox.x0 / ri.m_shrinkX, inBBox.y0 / ri.m_shrinkY); TTile tmp(TRaster32P(inBBoxLx, inBBoxLy), rasInPos); m_input->allocateAndCompute(tmp, rasInPos, TDimension(inBBoxLx, inBBoxLy), TRaster32P(), frame, ri); rasIn = tmp.getRaster(); } } unsigned int texWidth = 2; unsigned int texHeight = 2; while (texWidth < (unsigned int)inBBoxLx) texWidth = texWidth << 1; while (texHeight < (unsigned int)inBBoxLy) texHeight = texHeight << 1; while (texWidth > 1024 || texHeight > 1024) // avevo usato la costante // GL_MAX_TEXTURE_SIZE invece di // 1024, ma non funzionava! { inBBoxLx = inBBoxLx >> 1; inBBoxLy = inBBoxLy >> 1; texWidth = texWidth >> 1; texHeight = texHeight >> 1; } if (rasIn->getLx() != inBBoxLx || rasIn->getLy() != inBBoxLy) { TRaster32P rasOut = TRaster32P(inBBoxLx, inBBoxLy); TRop::resample(rasOut, rasIn, TScale((double)rasOut->getLx() / rasIn->getLx(), (double)rasOut->getLy() / rasIn->getLy())); rasIn = rasOut; } int rasterWidth = tile.getRaster()->getLx() + 2; int rasterHeight = tile.getRaster()->getLy() + 2; assert(rasterWidth > 0); assert(rasterHeight > 0); TRectD clippingRect = TRectD(tile.m_pos, TDimensionD(tile.getRaster()->getLx(), tile.getRaster()->getLy())); #ifdef CREATE_GL_CONTEXT_ONE_TIME int ret = wglMakeCurrent(m_offScreenGL.m_offDC, m_offScreenGL.m_hglRC); assert(ret == TRUE); #else TOfflineGL offScreenRendering(TDimension(rasterWidth, rasterHeight)); //#ifdef _WIN32 offScreenRendering.makeCurrent(); //#else //#if defined(LINUX) || defined(MACOSX) // offScreenRendering.m_offlineGL->makeCurrent(); //#endif #endif checkErrorsByGL // disabilito quello che non mi serve per le texture glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); glDisable(GL_DITHER); glDisable(GL_DEPTH_TEST); glCullFace(GL_FRONT); glDisable(GL_STENCIL_TEST); glDisable(GL_LOGIC_OP); // creo la texture in base all'immagine originale glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); checkErrorsByGL #ifndef CREATE_GL_CONTEXT_ONE_TIME TRaster32P rasaux; if (!wireframe) { TRaster32P texture(texWidth, texHeight); texture->clear(); rasaux = texture; rasaux->lock(); texture->copy(rasIn); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, 4, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture->getRawData()); } #else unsigned int texWidth = 1024; unsigned int texHeight = 1024; rasaux = rasIn; rasaux->lock(); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, rasIn->getLx(), rasIn->getLy(), GL_RGBA, GL_UNSIGNED_BYTE, rasIn->getRawData()); #endif checkErrorsByGL glEnable(GL_TEXTURE_2D); // cfr. help: OpenGL/Programming tip/OpenGL Correctness Tips glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-rasterWidth * 0.5, rasterWidth * 0.5, -rasterHeight * 0.5, rasterHeight * 0.5, -1, 1); glViewport(0, 0, rasterWidth, rasterHeight); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); // do OpenGL draw double lwTex = (double)(inBBoxLx - 1) / (double)(texWidth - 1); double lhTex = (double)(inBBoxLy - 1) / (double)(texHeight - 1); TPointD tex00 = TPointD(0.0, 0.0); TPointD tex10 = TPointD(lwTex, 0.0); TPointD tex11 = TPointD(lwTex, lhTex); TPointD tex01 = TPointD(0.0, lhTex); GLenum polygonStyle; if (wireframe) { polygonStyle = GL_LINE; glDisable(GL_TEXTURE_2D); } else polygonStyle = GL_FILL; checkErrorsByGL p00.x /= ri.m_shrinkX; p00.y /= ri.m_shrinkY; p10.x /= ri.m_shrinkX; p10.y /= ri.m_shrinkY; p11.x /= ri.m_shrinkX; p11.y /= ri.m_shrinkY; p01.x /= ri.m_shrinkX; p01.y /= ri.m_shrinkY; TPointD translate = TPointD(tile.m_pos.x + tile.getRaster()->getLx() * 0.5, tile.m_pos.y + tile.getRaster()->getLy() * 0.5); glTranslated(-translate.x, -translate.y, 0.0); // disegno il poligono double dist_p00_p01 = tdistance2(p00, p01); double dist_p10_p11 = tdistance2(p10, p11); double dist_p01_p11 = tdistance2(p01, p11); double dist_p00_p10 = tdistance2(p00, p10); bool vertical = (dist_p00_p01 == dist_p10_p11); bool horizontal = (dist_p00_p10 == dist_p01_p11); if (vertical && horizontal) details = 1; glPolygonMode(GL_FRONT_AND_BACK, polygonStyle); subdivision(p00, p10, p11, p01, tex00, tex10, tex11, tex01, clippingRect, details); if (!wireframe) { // abilito l'antialiasing delle linee glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // disegno il bordo del poligono glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBegin(GL_QUADS); glTexCoord2d(tex00.x, tex00.y); tglVertex(p00); glTexCoord2d(tex10.x, tex10.y); tglVertex(p10); glTexCoord2d(tex11.x, tex11.y); tglVertex(p11); glTexCoord2d(tex01.x, tex01.y); tglVertex(p01); glEnd(); // disabilito l'antialiasing per le linee glDisable(GL_LINE_SMOOTH); glDisable(GL_BLEND); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D); } // force to finish glFlush(); // rimetto il disegno dei poligoni a GL_FILL glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // metto il frame buffer nel raster del tile glPixelStorei(GL_UNPACK_ROW_LENGTH, rasterWidth); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); TRaster32P newRas(tile.getRaster()->getLx(), tile.getRaster()->getLy()); newRas->lock(); glReadPixels(1, 1, newRas->getLx(), newRas->getLy(), GL_RGBA, GL_UNSIGNED_BYTE, (void *)newRas->getRawData()); newRas->unlock(); checkErrorsByGL rasaux->unlock(); tile.getRaster()->copy(newRas); }
bool Framebuffer::init(bool gen) { //~ printf("init framebuffer with gen %u\n", gen); fflush(stdout); if (gen) { glGenFramebuffers(1, &id_); } if (params_.numMrts == 0) { printf("num mrts is zero, failed!\n"); fflush(stdout); return false; } if (params_.depth > GL_MAX_COLOR_ATTACHMENTS) { // same for mrt printf("num mrts is too many, failed\n"); fflush(stdout); return false; } bind(); // NSIGHT doesn't support this, seems to work without it anyways (since we aren't using empty framebuffers) //glFramebufferParameteri(GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_WIDTH, params_.width); //glFramebufferParameteri(GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_HEIGHT, params_.height); if (params_.colorEnable) { if (gen) { color_ = new GLuint[params_.numMrts]; } if (params_.type == GL_TEXTURE_2D) { //~ printf("making non-msaa 2d framebuffer\n"); fflush(stdout); if (gen) { glGenTextures(params_.numMrts, &color_[0]); } for (unsigned int i = 0; i < params_.numMrts; i++) { //printf("making non msaa color target for id %u\n", color_[i]); fflush(stdout); glBindTexture(GL_TEXTURE_2D, color_[i]); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, params_.filter); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, params_.filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexImage2D(GL_TEXTURE_2D, 0, params_.format, params_.width, params_.height, 0, GL_RGBA, GL_FLOAT, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, color_[i], 0); } } else if (params_.type == GL_TEXTURE_2D_MULTISAMPLE) { GLint maxSamples = 0; glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); params_.numSamples = min(params_.numSamples, static_cast<GLuint>(maxSamples)); if (gen) { glGenTextures(params_.numMrts, &color_[0]); } for (int i = 0; i < params_.numMrts; i++) { //~ printf("making msaa color target for id %u\n", color_[i]); fflush(stdout); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, color_[i]); //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, params_.numSamples, params_.format , params_.width, params_.height, false); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D_MULTISAMPLE, color_[i], 0); } } else if (params_.type == GL_TEXTURE_3D) { //~ printf("making non-msaa 3d framebuffer\n"); fflush(stdout); if (gen) { glGenTextures(params_.numMrts, &color_[0]); } for (int i = 0; i < params_.numMrts; i++) { glBindTexture(GL_TEXTURE_3D, color_[i]); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // must be linear or nearest glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage3D(GL_TEXTURE_3D, 0, params_.format, params_.width, params_.height, params_.depth, 0, GL_RGBA, GL_FLOAT, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, color_[i], 0); } /* binding each layer to a color attachment (old way) for (int i = 0; i < params_.depth; i++) { glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, color_[0], 0, i); } */ } GLenum *bufs = new GLenum[params_.numMrts]; for (unsigned int i = 0; i < params_.numMrts; i++) { bufs[i] = GL_COLOR_ATTACHMENT0 + i; } glDrawBuffers(params_.numMrts, bufs); delete[] bufs; glBindTexture(params_.type, 0); } if(params_.depthEnable) { if (gen) { glGenTextures(1, &depth_); } if (params_.type == GL_TEXTURE_2D_MULTISAMPLE) { //~ printf("making msaa z target id for %u\n", depth_); fflush(stdout); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, depth_); //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // this was throwing GL debug errors, so maybe take care of it in a sampler, or when we are doing shadow mapping? //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); //~ glTexParameteri(GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, params_.numSamples, params_.depthFormat, params_.width, params_.height, false); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, depth_, 0); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); } else if (params_.type == GL_TEXTURE_3D) { glBindTexture(GL_TEXTURE_3D, depth_); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexImage3D(GL_TEXTURE_3D, 0, params_.depthFormat, params_.width, params_.height, params_.depth, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depth_, 0); glBindTexture(GL_TEXTURE_3D, 0); } else { //printf("making normal z target for id %u\n", depth_); fflush(stdout); glBindTexture(GL_TEXTURE_2D, depth_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); // glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_STENCIL_TEXTURE_MODE, GL_DEPTH_COMPONENT); // should be default glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // comparison functions for shadow mapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexImage2D(GL_TEXTURE_2D, 0, params_.depthFormat, params_.width, params_.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_, 0); glBindTexture(GL_TEXTURE_2D, 0); } } bool check = checkStatus(GL_FRAMEBUFFER); glBindFramebuffer(GL_FRAMEBUFFER, 0); return check; }
/* Create a texture in OpenGL. First an image is loaded and stored in a raster buffer, then it's */ static void Create_Texture(ModeInfo *mi, const char *filename) { int height, width; GLubyte *image; int format; if ( !strncmp(filename, "BUILTIN", 7)) image = Generate_Image(&width, &height, &format); else { XImage *ximage = xpm_file_to_ximage (MI_DISPLAY (mi), MI_VISUAL (mi), MI_COLORMAP (mi), filename); image = (GLubyte *) ximage->data; width = ximage->width; height = ximage->height; format = GL_RGBA; } /* GL_MODULATE or GL_DECAL depending on what you want */ glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); /* perhaps we can edge a bit more speed at the expense of quality */ glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); if (do_texture_quality) { /* with texture_quality, the min and mag filters look *much* nice but are *much* slower */ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { /* default is to do it quick and dirty */ /* if you have mipmaps turned on, but not texture quality, nothing will happen! */ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } /* mipmaps make the image look much nicer */ if (do_mipmap) { int status; clear_gl_error(); status = gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height, format, GL_UNSIGNED_BYTE, image); if (status) { const char *s = (char *) gluErrorString (status); fprintf (stderr, "%s: error mipmapping %dx%d texture: %s\n", progname, width, height, (s ? s : "(unknown)")); exit (1); } check_gl_error("mipmapping"); } else { clear_gl_error(); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, image); check_gl_error("texture"); } }
int LoadBitmap(char *filename) { FILE * file; char temp; long i; // own version of BITMAPINFOHEADER from windows.h for Linux compile struct { int biWidth; int biHeight; short int biPlanes; unsigned short int biBitCount; unsigned char *data; } infoheader; GLuint num_texture; if( (file = fopen(filename, "rb"))==NULL) return (-1); // Open the file for reading fseek(file, 18, SEEK_CUR); /* start reading width & height */ fread(&infoheader.biWidth, sizeof(int), 1, file); fread(&infoheader.biHeight, sizeof(int), 1, file); fread(&infoheader.biPlanes, sizeof(short int), 1, file); if (infoheader.biPlanes != 1) { printf("Planes from %s is not 1: %u\n", filename, infoheader.biPlanes); return 0; } // read the bpp fread(&infoheader.biBitCount, sizeof(unsigned short int), 1, file); if (infoheader.biBitCount != 24) { printf("Bpp from %s is not 24: %d\n", filename, infoheader.biBitCount); return 0; } fseek(file, 24, SEEK_CUR); // read the data if(infoheader.biWidth<0){ infoheader.biWidth = -infoheader.biWidth; } if(infoheader.biHeight<0){ infoheader.biHeight = -infoheader.biHeight; } infoheader.data = (unsigned char *) malloc(infoheader.biWidth * infoheader.biHeight * 3); if (infoheader.data == NULL) { printf("Error allocating memory for color-corrected image data\n"); return 0; } if ((i = fread(infoheader.data, infoheader.biWidth * infoheader.biHeight * 3, 1, file)) != 1) { printf("Error reading image data from %s.\n", filename); return 0; } for (i=0; i<(infoheader.biWidth * infoheader.biHeight * 3); i+=3) { // reverse all of the colors. (bgr -> rgb) temp = infoheader.data[i]; infoheader.data[i] = infoheader.data[i+2]; infoheader.data[i+2] = temp; } fclose(file); // Closes the file stream glGenTextures(1, &num_texture); glBindTexture(GL_TEXTURE_2D, num_texture); // Bind the ID texture specified by the 2nd parameter // The next commands sets the texture parameters glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // If the u,v coordinates overflow the range 0,1 the image is repeated glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // The magnification function ("linear" produces better results) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); //The minifying function glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // Finally we define the 2d texture glTexImage2D(GL_TEXTURE_2D, 0, 3, infoheader.biWidth, infoheader.biHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, infoheader.data); // And create 2d mipmaps for the minifying function gluBuild2DMipmaps(GL_TEXTURE_2D, 3, infoheader.biWidth, infoheader.biHeight, GL_RGB, GL_UNSIGNED_BYTE, infoheader.data); free(infoheader.data); // Free the memory we used to load the texture return (num_texture); // Returns the current texture OpenGL ID }
void myinit(void) { // Load shaders and use the resulting shader program GLuint program = InitShader( "vshader.glsl", "fshader.glsl" ); glUseProgram(program); // Generate vertex arrays for geometric shapes generateCube(program, &cubeData); generateSphere(program, &sphereData); generateCone(program, &coneData); generateCylinder(program, &cylData); generatePyramid(program, &pyramidData); uModelView = glGetUniformLocation( program, "ModelView" ); uProjection = glGetUniformLocation( program, "Projection" ); uView = glGetUniformLocation( program, "View" ); glClearColor( .1, .1, .6, 1.0 ); // dark blue background uAmbient = glGetUniformLocation( program, "AmbientProduct" ); uDiffuse = glGetUniformLocation( program, "DiffuseProduct" ); uSpecular = glGetUniformLocation( program, "SpecularProduct" ); uLightPos = glGetUniformLocation( program, "LightPosition" ); uShininess = glGetUniformLocation( program, "Shininess" ); uTex = glGetUniformLocation( program, "Tex" ); uEnableTex = glGetUniformLocation( program, "EnableTex" ); glUniform4f(uAmbient, 0.2f, 0.2f, 0.2f, 1.0f); glUniform4f(uDiffuse, 0.6f, 0.6f, 0.6f, 1.0f); glUniform4f(uSpecular, 0.2f, 0.2f, 0.2f, 1.0f); glUniform4f(uLightPos, 15.0f, 15.0f, 30.0f, 0.0f); glUniform1f(uShininess, 100.0f); glEnable(GL_DEPTH_TEST); TgaImage coolImage; if (!coolImage.loadTGA("dirt.tga")) { printf("Error loading image file\n"); exit(1); } TgaImage earthImage; if (!earthImage.loadTGA("earth.tga")) { printf("Error loading image file\n"); exit(1); } TgaImage roofImage; if (!roofImage.loadTGA("roof.tga")) { printf("Error loading image file\n"); exit(1); } TgaImage treeImage; if (!treeImage.loadTGA("tree.tga")) { printf("Error loading image file\n"); exit(1); } TgaImage skyImage; if (!skyImage.loadTGA("sky.tga")) { printf("Error loading image file\n"); exit(1); } TgaImage stoneImage; if (!stoneImage.loadTGA("stone.tga")) { printf("Error loading image file\n"); exit(1); } TgaImage leafImage; if (!leafImage.loadTGA("leaf.tga")) { printf("Error loading image file\n"); exit(1); } glGenTextures( 1, &texture_cube ); glBindTexture( GL_TEXTURE_2D, texture_cube ); glTexImage2D(GL_TEXTURE_2D, 0, 4, coolImage.width, coolImage.height, 0, (coolImage.byteCount == 3) ? GL_BGR : GL_BGRA, GL_UNSIGNED_BYTE, coolImage.data ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glGenTextures( 1, &texture_earth ); glBindTexture( GL_TEXTURE_2D, texture_earth ); glTexImage2D(GL_TEXTURE_2D, 0, 4, earthImage.width, earthImage.height, 0, (earthImage.byteCount == 3) ? GL_BGR : GL_BGRA, GL_UNSIGNED_BYTE, earthImage.data ); //roof glGenTextures( 1, &texture_roof ); glBindTexture( GL_TEXTURE_2D, texture_roof ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexImage2D(GL_TEXTURE_2D, 0, 4, roofImage.width, roofImage.height, 0, (roofImage.byteCount == 3) ? GL_BGR : GL_BGRA, GL_UNSIGNED_BYTE, roofImage.data ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glGenTextures( 1, &texture_trees ); glBindTexture( GL_TEXTURE_2D, texture_trees ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexImage2D(GL_TEXTURE_2D, 0, 4, treeImage.width, treeImage.height, 0, (treeImage.byteCount == 3) ? GL_BGR : GL_BGRA, GL_UNSIGNED_BYTE, treeImage.data ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glGenTextures( 1, &texture_leaf ); glBindTexture( GL_TEXTURE_2D, texture_leaf ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexImage2D(GL_TEXTURE_2D, 0, 4, leafImage.width, leafImage.height, 0, (leafImage.byteCount == 3) ? GL_BGR : GL_BGRA, GL_UNSIGNED_BYTE, leafImage.data ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glGenTextures( 1, &texture_stone ); glBindTexture( GL_TEXTURE_2D, texture_stone ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexImage2D(GL_TEXTURE_2D, 0, 4, stoneImage.width, stoneImage.height, 0, (stoneImage.byteCount == 3) ? GL_BGR : GL_BGRA, GL_UNSIGNED_BYTE, stoneImage.data ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); // Set texture sampler variable to texture unit 0 // (set in glActiveTexture(GL_TEXTURE0)) glUniform1i( uTex, 0); Arcball = new BallData; Ball_Init(Arcball); Ball_Place(Arcball,qOne,0.75); }
bool TextureManager::TImpl::ItlLoadTextureFromFile(GLuint &rnTextureID, std::string sFilename, bool bAlreadyGammaCorrected) { Logger::debug() << "Try to load texture from \"" << sFilename << "\"" << Logger::endl; ILuint nIlTextureId; // index für DevIL Textur ilGenImages(1,&nIlTextureId); // generieren von IL ID für Texturen ilBindImage(nIlTextureId); // bestimmten Texturindex als aktell setzen if (!ilLoadImage (sFilename.data())) // laden der Textur { ILenum Error; Error = ilGetError(); ilDeleteImages(1,&nIlTextureId); // bei Fehlschlag wieder Index freigeben Logger::error() << "Could not find texture file " << sFilename << ", loading failed. DevIL error-code: " << Error << Logger::endl; return false; } else { long int iHeight, iWidth, iFormat; unsigned char *szData=0; iWidth=ilGetInteger(IL_IMAGE_WIDTH); // Breite des Bildes holen iHeight=ilGetInteger(IL_IMAGE_HEIGHT); // Höhe des Bildes holen //bpp=ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL); // Farbtiefe des Bildes iFormat=ilGetInteger(IL_IMAGE_FORMAT); // Format des Bildes z.B. RGB RGBA BGR BGRA usw. szData=ilGetData(); // Zeiger auf Bilddaten holen glGetError(); // clear error state glGenTextures(1,&rnTextureID); // ask for opengl texture-id (returns first free id) glBindTexture(GL_TEXTURE_2D, rnTextureID); if (bAlreadyGammaCorrected) glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, iWidth, iHeight, 0, iFormat, GL_UNSIGNED_BYTE, szData); else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, iWidth, iHeight, 0, iFormat, GL_UNSIGNED_BYTE, szData); //activate mipmapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); float fMaximumAnisotropy=0.0; //get maximum ansitropic filtering value glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fMaximumAnisotropy); //activate 4x ansitropic filtering if possible if (fMaximumAnisotropy >= 1.0) { if (fMaximumAnisotropy > 4.0) fMaximumAnisotropy = 4.0f; glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fMaximumAnisotropy); Logger::debug() << fMaximumAnisotropy << " ansitropic filtering activated" << Logger::endl; } else Logger::error() << "Ansitropic filtering not available by graphic hardware" << Logger::endl; glGenerateMipmap(GL_TEXTURE_2D); //Generate mipmaps now!!! GLenum eError = glGetError(); if (eError != GL_NO_ERROR) Logger::error() << "glGetError: " << GLUtils::TranslateGLerror(eError) << Logger::endl; return true; } }
static void pinit(ModeInfo *mi) { /* int status; */ glClearDepth(1.0); glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0, GL_POSITION, position0); glLightfv(GL_LIGHT1, GL_AMBIENT, ambient); glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT1, GL_POSITION, position1); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient); glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glEnable(GL_NORMALIZE); glCullFace(GL_BACK); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialWhite); glShadeModel(GL_FLAT); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); #if 0 clear_gl_error(); status = gluBuild2DMipmaps(GL_TEXTURE_2D, 3, WoodTextureWidth, WoodTextureHeight, GL_RGB, GL_UNSIGNED_BYTE, WoodTextureData); if (status) { const char *s = (char *) gluErrorString (status); fprintf (stderr, "%s: error mipmapping %dx%d texture: %s\n", progname, WoodTextureWidth, WoodTextureHeight, (s ? s : "(unknown)")); exit (1); } check_gl_error("mipmapping"); #else { XImage *img = image_data_to_ximage (mi->dpy, mi->xgwa.visual, wood_png, sizeof(wood_png)); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, img->width, img->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img->data); check_gl_error("texture"); XDestroyImage (img); } #endif glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, front_shininess); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, front_specular); }
/** loadTexture * loads a png file into an opengl texture object, using cstdio , libpng, and opengl. * * \param filename : the png file to be loaded * */ GLuint MeshUtil::loadTexture(zip* apk,const char* filename) { file = zip_fopen(apk, filename, 0); if (!file) { LOGI("Error opening %s from APK", filename); return TEXTURE_LOAD_ERROR; } //header for testing if it is a png png_byte header[8]; //read the header zip_fread(file, header, 8); //test if png int is_png = !png_sig_cmp(header, 0, 8); if (!is_png) { zip_fclose(file); LOGI("Not a png file : %s", filename); return TEXTURE_LOAD_ERROR; } //create png struct png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { zip_fclose(file); LOGI("Unable to create png struct : %s", filename); return (TEXTURE_LOAD_ERROR); } //create png info struct png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL); LOGI("Unable to create png info : %s", filename); zip_fclose(file); return (TEXTURE_LOAD_ERROR); } //create png info struct png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL); LOGI("Unable to create png end info : %s", filename); zip_fclose(file); return (TEXTURE_LOAD_ERROR); } //png error stuff, not sure libpng man suggests this. if (setjmp(png_jmpbuf(png_ptr))) { zip_fclose(file); LOGI("Error during setjmp : %s", filename); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return (TEXTURE_LOAD_ERROR); } //init png reading //png_init_io(png_ptr, fp); png_set_read_fn(png_ptr, NULL, png_zip_read); //let libpng know you already read the first 8 bytes png_set_sig_bytes(png_ptr, 8); // read all the info up to the image data png_read_info(png_ptr, info_ptr); //variables to pass to get info int bit_depth, color_type; png_uint_32 twidth, theight; // get info about png png_get_IHDR(png_ptr, info_ptr, &twidth, &theight, &bit_depth, &color_type, NULL, NULL, NULL); GLint texFormat = 0; //set the right texture format if(color_type == PNG_COLOR_TYPE_RGBA){ texFormat = GL_RGBA; }else if(color_type == PNG_COLOR_TYPE_RGB){ texFormat = GL_RGB; }else{ zip_fclose(file); LOGI("Texture color format is not supported"); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return TEXTURE_LOAD_ERROR; } // Update the png info struct. png_read_update_info(png_ptr, info_ptr); // Row size in bytes. int rowbytes = png_get_rowbytes(png_ptr, info_ptr); // Allocate the image_data as a big block, to be given to opengl png_byte *image_data = new png_byte[rowbytes * theight]; if (!image_data) { //clean up memory and close stuff png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); LOGI("Unable to allocate image_data while loading %s ", filename); zip_fclose(file); return TEXTURE_LOAD_ERROR; } //row_pointers is for pointing to image_data for reading the png with libpng png_bytep *row_pointers = new png_bytep[theight]; if (!row_pointers) { //clean up memory and close stuff png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); delete[] image_data; LOGI("Unable to allocate row_pointer while loading %s ", filename); zip_fclose(file); return TEXTURE_LOAD_ERROR; } // set the individual row_pointers to point at the correct offsets of image_data for (unsigned int i = 0; i < theight; ++i) row_pointers[theight - 1 - i] = image_data + i * rowbytes; //read the png into image_data through row_pointers png_read_image(png_ptr, row_pointers); //Now generate the OpenGL texture object GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); /*glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);*/ glTexImage2D(GL_TEXTURE_2D, 0, texFormat, twidth, theight, 0, texFormat, GL_UNSIGNED_BYTE, image_data); //glMatrixMode(GL_TEXTURE ); #ifdef USE_OPENGL_ES_1_1 glLoadIdentity(); #else #endif //clean up memory and close stuff png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); delete[] image_data; delete[] row_pointers; zip_fclose(file); return texture; }
void init(int buffer_width, int buffer_height) { frame_buffer_texture_width = buffer_width; frame_buffer_texture_height = buffer_height; #if defined(TARGET_OS_HARMATTAN) || defined(TARGET_PANDORA) || defined(TARGET_TEGRA) || defined(TARGET_BLACKBERRY) if (glGenFramebuffersOES != NULL && glBindFramebufferOES != NULL && glFramebufferTexture2DOES != NULL && glCheckFramebufferStatusOES != NULL) { supported = true; } else { fprintf(stderr, "FRAME BUFFER OBJECT NOT SUPPORTED\n"); supported = false; return; } #elif !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR if(!GLEW_EXT_framebuffer_object) { fprintf(stderr, "FRAME BUFFER OBJECT NOT SUPPORTED\n"); supported = false; return; } #endif fprintf(stderr, "FRAME BUFFER OBJECT IS SUPPORTED\n"); #ifndef TARGET_TEGRA glGetIntegerv(EXT_MACRO(GL_FRAMEBUFFER_BINDING), &video_framebuffer_id); #endif ASSERT_EQ(glGetError(), GL_NO_ERROR); glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width(), height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); // create a framebuffer object EXT_CALL(glGenFramebuffers)(1, &framebuffer_id); EXT_CALL(glBindFramebuffer)(EXT_MACRO(GL_FRAMEBUFFER), framebuffer_id); // attach the texture to FBO color attachment point EXT_CALL(glFramebufferTexture2D)(EXT_MACRO(GL_FRAMEBUFFER), EXT_MACRO(GL_COLOR_ATTACHMENT0), GL_TEXTURE_2D, texture_id, 0); // check FBO status GLenum status = EXT_CALL(glCheckFramebufferStatus)(EXT_MACRO(GL_FRAMEBUFFER)); ASSERT_EQ(status, EXT_MACRO(GL_FRAMEBUFFER_COMPLETE)); // switch back to window-system-provided framebuffer EXT_CALL(glBindFramebuffer)(EXT_MACRO(GL_FRAMEBUFFER), video_framebuffer_id); ASSERT_EQ(glGetError(), GL_NO_ERROR); }
void main_window::initializeGL ( ) { glDepthFunc(GL_LEQUAL); glGenTextures(1, &texture_id); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_id); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); auto random = std::bind(std::uniform_int_distribution<unsigned char>(192, 255), std::default_random_engine()); for (int x = 0; x < texture_size; ++x) { for (int y = 0; y < texture_size; ++y) { unsigned char value = random(); bool border = false; //x == 0 || x == texture_size - 1 || y == 0 || y == texture_size - 1; int border_value = 127; texture[x * texture_size * 3 + y * 3 + 0] = border ? border_value : value; texture[x * texture_size * 3 + y * 3 + 1] = border ? border_value : value; texture[x * texture_size * 3 + y * 3 + 2] = border ? border_value : value; } } glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, 3, texture_size, texture_size, 0, GL_RGB, GL_UNSIGNED_BYTE, texture); const char * vertex_shader_code = "\ uniform vec4 relocate; \ varying vec2 texCoord; \ varying vec4 position; \ varying vec4 normal; \ uniform vec4 playerPos; \ void main() { \ if (dot(gl_Vertex - playerPos, gl_Vertex - playerPos) < 0.0) { } \ gl_Position = gl_ModelViewProjectionMatrix * (gl_Vertex + relocate); \ position = gl_Vertex; \ normal = vec4(gl_Normal, 0.0); \ gl_FrontColor = gl_Color; \ gl_BackColor = gl_Color; \ texCoord = gl_MultiTexCoord0.xy; \ }"; const char * fragment_shader_code = "\ uniform float health; \ uniform sampler2D texture; \ varying vec2 texCoord; \ vec4 texColor; \ varying vec4 position; \ varying vec4 normal; \ uniform vec4 playerPos; \ vec4 delta; \ float light; \ void main() { \ delta = playerPos - position; \ delta[3] = 0.0; \ light = dot(normalize(delta), normal); \ texColor = texture2D(texture, texCoord); \ gl_FragColor[0] = texColor[0] * gl_Color[0]; \ gl_FragColor[1] = texColor[1] * gl_Color[1]; \ gl_FragColor[2] = texColor[2] * gl_Color[2]; \ gl_FragColor[3] = texColor[3] * gl_Color[3]; \ if (texCoord[0] < 1.0 / 32.0 || texCoord[0] > 31.0 / 32.0 || texCoord[1] < 1.0 / 32.0 || texCoord[1] > 31.0 / 32.0) \ { \ gl_FragColor = mix(gl_FragColor, vec4(0.0, 0.0, 0.0, 1.0), 0.5); \ } \ gl_FragColor = mix(vec4(0.75, 0.75, 0.75, 1.0), gl_FragColor, min(10.0 / dot(delta, delta), 1.0)); \ gl_FragColor[0] = gl_FragColor[0] + health * (1.0 - gl_FragColor[0]); \ gl_FragColor[1] = gl_FragColor[1] + health * (0.0 - gl_FragColor[1]); \ gl_FragColor[2] = gl_FragColor[2] + health * (0.0 - gl_FragColor[2]); \ }";
void LoadTextureAMT::processGPU_Texture2D() { ImageReader* reader = m_imageReaders[0]; if(!reader) { return; } glActiveTexture(GL_TEXTURE0); glGenTextures(1, &m_textureId); glBindTexture(m_target, m_textureId); int levels; if(m_loadMipmaps) { levels = reader->getLevelAmount(); if(levels == 1) { // If need mipmaps and image has only base level, set number of mipmap levels to generate levels = gmath::imageLevelCount(reader->getWidth(0), reader->getHeight(0), 1); } } else { levels = 1; } glTexStorage2D(m_target, levels, m_imageGLFormat, reader->getWidth(0), reader->getHeight(0)); for(int i = 0; i < reader->getLevelAmount(); i++) { if(reader->isCompressedFormat()) { glCompressedTexSubImage2D(m_target, i, 0, 0, reader->getWidth(i), reader->getHeight(i), reader->getFormat(), reader->getLevelSize(i), reader->getData(i)); } else { glTexSubImage2D(m_target, i, 0, 0, reader->getWidth(i), reader->getHeight(i), reader->getFormat(), GL_UNSIGNED_BYTE, reader->getData(i)); } } glTexParameteri(m_target, GL_TEXTURE_BASE_LEVEL, 0); if((reader->getLevelAmount() == 1) && m_loadMipmaps) { glGenerateMipmap(m_target); } if(m_loadMipmaps) { glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(m_target, GL_TEXTURE_MAX_LEVEL, 0); } // Anisotropy filtering float maximumAnistropy; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maximumAnistropy); glTexParameterf(m_target, GL_TEXTURE_MAX_ANISOTROPY_EXT, maximumAnistropy); glBindTexture(m_target, 0); utils::deleteAndNull(reader); m_imageReaders[0] = nullptr; m_context->m_target = m_target; m_context->m_textureId = m_textureId; }