int GLAppMain::init() { goon = 1; pos = vec3(0,0.5,5); lookat = vec3(0,0,-1); font = new Font("../textures/font.png"); //img = new Texture( "data/papuanewguinea.png" ); img = new Texture("../textures/kiribati.png"); /* create a pbuffer and some vertex buffers */ pbuffer = new PBuffer( SIZE, SIZE, PBuffer::RGBA | PBuffer::FLOAT32 ); vertex_buffer = new Buffer( SIZE*SIZE*4*sizeof(float), GL_DYNAMIC_COPY_ARB ); normal_buffer = new Buffer( SIZE*SIZE*4*sizeof(float), GL_DYNAMIC_COPY_ARB ); /* calculate indices buffer data */ unsigned int *indices; indices = (unsigned int*)malloc(SIZE*(SIZE-1)*2*sizeof(unsigned int)); for(unsigned int j=0;j<SIZE-1;j++) for(unsigned int i=0;i<SIZE;i++) { if(j&1){ indices[j*SIZE*2+2*i+1] = SIZE-1-i +j*SIZE; indices[j*SIZE*2+2*i] = SIZE-1-i+SIZE +j*SIZE; } else { indices[j*SIZE*2+2*i+1] = i+SIZE +j*SIZE; indices[j*SIZE*2+2*i] = i +j*SIZE; } } index_buffer = new Buffer( SIZE*(SIZE-1)*2*sizeof(unsigned int), GL_STATIC_DRAW_ARB, indices ); free(indices); /* calculate texcoords buffer data */ vec2 *textures; textures = (vec2*)malloc(SIZE*SIZE*sizeof(vec2)); for(unsigned int j=0;j<SIZE;j++) for(unsigned int i=0;i<SIZE;i++) textures[i+j*SIZE] = vec2((i+0.5)/SIZE,(j+0.5)/SIZE); texcoord_buffer = new Buffer( SIZE*SIZE*sizeof(vec2), GL_STATIC_DRAW_ARB, textures ); free(textures); /* calculate positions texture data */ vec4 *pos; pos = (vec4*)malloc(SIZE*SIZE*sizeof(vec4)); for(unsigned int j=0;j<SIZE;j++) for(unsigned int i=0;i<SIZE;i++) pos[i+j*SIZE] = vec4(4.0*i/(SIZE-1)-2.0,1.0,4.0*j/(SIZE-1)-2.0,0.0); positions = new Texture( SIZE, SIZE, Texture::TEXTURE_2D, Texture::CLAMP | Texture::RGBA | Texture::NEAREST | Texture::FLOAT32, pos ); /* calculate speeds texture data */ for(unsigned int j=0;j<SIZE;j++) for(unsigned int i=0;i<SIZE;i++) pos[i+j*SIZE] = vec4(0.0,0.0,0.0,0.0); speeds = new Texture( SIZE, SIZE, Texture::TEXTURE_2D, Texture::RGBA | Texture::NEAREST | Texture::FLOAT32, pos ); /* calculate normals texture data */ for(unsigned int j=0;j<SIZE;j++) for(unsigned int i=0;i<SIZE;i++) pos[i+j*SIZE] = vec4(0.0,1.0,0.0,0.0); normals = new Texture( SIZE, SIZE, Texture::TEXTURE_2D, Texture::RGBA | Texture::NEAREST | Texture::FLOAT32, pos ); free(pos); /* load shaders */ char header[127]; sprintf(header,"#define SIZE %d\n#define LINK %d\n", SIZE, SIZE<=64 ? 2 : (SIZE>=256 ? 4 : 3)); positions_shader = new Shader("../data/shaders/positions.vert", "../data/shaders/positions.frag",header); positions_shader->bind(); positions_shader->setUniform("positions",0); positions_shader->setUniform("speeds",1); positions_shader->setUniform("normals",2); positions_shader->unbind(); speeds_shader = new Shader("../data/shaders/speeds.vert", "../data/shaders/speeds.frag",header); speeds_shader->bind(); speeds_shader->setUniform("speeds",0); speeds_shader->setUniform("speeds",1); speeds_shader->setUniform("normals",2); speeds_shader->unbind(); normals_shader = new Shader("../data/shaders/normals.vert", "../data/shaders/normals.frag",header); normals_shader->bind(); normals_shader->setUniform("normals",0); normals_shader->setUniform("normals",1); normals_shader->setUniform("normals",2); normals_shader->unbind(); /* init the state in the pbuffer */ pbuffer->enable(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,1,0,1,-1,1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); pbuffer->disable(); /* init the state in the main context */ glClearColor( 0.2, 0.3, 0.4, 0 ); return 1; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { #else int main(int argc, char** argv) { #endif Window window("Sample_BurningPaper", 1024, 768, true); RenderParameters_t renderParameters; renderParameters.width = 1024; renderParameters.height = 768; renderParameters.displayFormat = DISPLAY_FORMAT_X8R8G8B8; renderParameters.refreshRate = 0; renderParameters.depthStencilBits = DEPTH_STENCIL_BITS_D24X8; Renderer::GetInstance()->Initialize(RENDER_SYSTEM_OPENGL, window, renderParameters); Renderer::GetInstance()->SetClearColor(0.2f, 0.2f, 0.2f); // Create the paper surface SurfaceTriangles_t surface; surface.numVertices = 4; surface.numTexCoords = 4; surface.numIndices = 6; surface.vertices = new Vector3[surface.numVertices]; surface.texCoords = new Vector2[surface.numTexCoords]; surface.indices = new unsigned short[surface.numIndices]; surface.vertices[0] = Vector3(-1.2f, -1.5f, 1.0f); surface.vertices[1] = Vector3(-1.2f, 1.5f, 1.0f); surface.vertices[2] = Vector3(1.2f, 1.5f, 1.0f); surface.vertices[3] = Vector3(1.2f, -1.5f, 1.0f); surface.texCoords[0] = Vector2(0.0f, 0.0f); surface.texCoords[1] = Vector2(0.0f, 1.0f); surface.texCoords[2] = Vector2(1.0f, 1.0f); surface.texCoords[3] = Vector2(1.0f, 0.0f); surface.indices[0] = 0; surface.indices[1] = 2; surface.indices[2] = 1; surface.indices[3] = 0; surface.indices[4] = 3; surface.indices[5] = 2; Mesh paperMesh; paperMesh.AddSurface(&surface); VertexAttributesMap_t vertexAttributes; vertexAttributes[VERTEX_ATTRIBUTES_POSITION] = 0; vertexAttributes[VERTEX_ATTRIBUTES_TEX_COORDS] = 1; paperMesh.Initialize(vertexAttributes); // Create the paper material Shader* shader = Renderer::GetInstance()->CreateShader(); shader->SetSourceFile("Shaders/BurningPaper/vert", "Shaders/BurningPaper/frag"); Material paperMaterial(shader); Texture2D* paperTexture = Renderer::GetInstance()->CreateTexture2DFromFile("Media/paper.jpg"); Texture2D* noiseTexture = Renderer::GetInstance()->CreateTexture2DFromFile("Media/noise.jpg"); paperMaterial.SetUniformTexture("paper", paperTexture); paperMaterial.SetUniformTexture("noise", noiseTexture); // Create the paper node Node paperNode; paperNode.SetMaterial(&paperMaterial); paperNode.SetMesh(&paperMesh); Renderer::GetInstance()->GetSceneTree().AddNode(&paperNode); Renderer::GetInstance()->CameraLookAt(Vector3(0.0f, 0.0f, 5.0f), -Vector3::LOOK, Vector3::UP); float threshold = 0.0f; float range = 0.075f; float t = 0.0f; clock_t begin, end; #if PLATFORM == PLATFORM_WIN32 Text::GetInstance()->SetTextFont("C:/Windows/Fonts/Arial.ttf"); #elif PLATFORM == PLATFORM_LINUX Text::GetInstance()->SetTextFont("/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf"); #endif Text::GetInstance()->SetTextSize(24, 24); float fps = 0; float dt = 0.0f; size_t numFrames = 0; while (window.IsOpen()) { begin = clock(); WindowEvent windowEvent; if (window.PollEvents(windowEvent)) { } threshold += t / 3.0f; Renderer::GetInstance()->BindShader(shader); shader->SetUniformVector2("thresholds", threshold, range); Renderer::GetInstance()->Clear(); Renderer::GetInstance()->StartRender(); Renderer::GetInstance()->Render(); Text::GetInstance()->Write(to_string(fps), 5, 5); Renderer::GetInstance()->EndRender(); Renderer::GetInstance()->PresentFrame(); end = clock(); t = float(end - begin) / CLOCKS_PER_SEC; dt += float(end - begin) / CLOCKS_PER_SEC; numFrames += 1; if (dt >= 0.25f) { fps = (float)numFrames / dt; numFrames = 0; dt -= 0.25f; } } return 0; }
void Program::attachShader(Shader &shader) { gl::AttachShader(this->ref, shader.getRef()); }
virtual void loadShader (Shader& shader, string shader_name) { shader.load(shader_name, shaders_dir); shader.initialize(); shaders_list.push_back(&shader); }
GLuint blur( Shader blur, GLuint texture, int amount) { static bool createAll = true; static GLuint pingpongFBO[2]; static GLuint pingpongBuffer[2]; static GLuint vao; static GLuint vbo[2]; if(createAll) { int w, h; glBindTexture(GL_TEXTURE_2D, texture); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); std::cout << w << h << std::endl; glGenFramebuffers(2, pingpongFBO); glGenTextures(2, pingpongBuffer); for (GLuint i = 0; i < 2; i++) { glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[i]); glBindTexture(GL_TEXTURE_2D, pingpongBuffer[i]); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB16F, w, h, 0, GL_RGB, GL_FLOAT, NULL ); 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_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pingpongBuffer[i], 0 ); } int quad_triangleCount = 2; int quad_triangleList[] = {0, 1, 2, 2, 1, 3}; float quad_vertices[] = {-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0}; // Quad glBindVertexArray(vao); // Bind indices and upload data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quad_triangleList), quad_triangleList, GL_STATIC_DRAW); // Bind vertices and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), quad_vertices, GL_STATIC_DRAW); createAll = false; } GLboolean horizontal = true, first_iteration = true; amount = amount + (amount%2); blur.use(); for (GLuint i = 0; i < amount; i++) { glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[horizontal]); glUniform1i(glGetUniformLocation(blur.getProgram(), "horizontal"), horizontal); glBindTexture( GL_TEXTURE_2D, first_iteration ? texture : pingpongBuffer[!horizontal] ); glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void*)0); horizontal = !horizontal; if (first_iteration) first_iteration = false; } glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); Utils::checkGlError("blur"); return pingpongBuffer[!horizontal]; }
// --[ Method ]--------------------------------------------------------------- // // - Class : CStravaganzaMaxTools // // - prototype : bool BuildShaders() // // - Purpose : Builds the shader list from MAX's materials. // Preview mode requires texture files to be stored with full // path in order to load them. When we export, we only store the // filename. Another thing is that in the export mode, we copy // all textures into the path specified by the user if that // option is checked. // // ----------------------------------------------------------------------------- bool CStravaganzaMaxTools::BuildShaders() { std::vector<Mtl*>::iterator it; assert(m_vecShaders.empty()); if(!m_bPreview && m_bCopyTextures && m_strTexturePath == "") { CLogger::NotifyWindow("Textures won't be copied\nSpecify a valid output texture path first"); } LOG.Write("\n\n-Building shaders: "); for(it = m_vecMaterials.begin(); it != m_vecMaterials.end(); ++it) { Mtl* pMaxMaterial = *it; assert(pMaxMaterial); LOG.Write("\n %s", pMaxMaterial->GetName().data()); CShaderStandard* pShaderStd = new CShaderStandard; pShaderStd->SetName(pMaxMaterial->GetName().data()); // Properties StdMat2 *pMaxStandardMtl = NULL; StdMat2 *pMaxBakedMtl = NULL; float fAlpha; if(pMaxMaterial->ClassID() == Class_ID(DMTL_CLASS_ID, 0)) { pMaxStandardMtl = (StdMat2 *)pMaxMaterial; } else if(pMaxMaterial->ClassID() == Class_ID(BAKE_SHELL_CLASS_ID, 0)) { pMaxStandardMtl = (StdMat2 *)pMaxMaterial->GetSubMtl(0); pMaxBakedMtl = (StdMat2 *)pMaxMaterial->GetSubMtl(1); } if(pMaxStandardMtl) { // Standard material fAlpha = pMaxStandardMtl->GetOpacity(0); Shader* pMaxShader = pMaxStandardMtl->GetShader(); CVector4 v4Specular = ColorToVector4(pMaxStandardMtl->GetSpecular(0), 0.0f) * pMaxShader->GetSpecularLevel(0, 0); pShaderStd->SetAmbient (ColorToVector4(pMaxStandardMtl->GetAmbient(0), 0.0f)); pShaderStd->SetDiffuse (ColorToVector4(pMaxStandardMtl->GetDiffuse(0), fAlpha)); pShaderStd->SetSpecular (v4Specular); pShaderStd->SetShininess(pMaxShader->GetGlossiness(0, 0) * 128.0f); if(pMaxStandardMtl->GetTwoSided() == TRUE) { pShaderStd->SetTwoSided(true); } // Need to cast to StdMat2 in order to get access to IsFaceted(). // ¿Is StdMat2 always the interface for standard materials? if(((StdMat2*)pMaxStandardMtl)->IsFaceted()) { pShaderStd->SetFaceted(true); } if(pMaxStandardMtl->GetWire() == TRUE) { pShaderStd->SetPostWire(true); pShaderStd->SetWireLineThickness(pMaxStandardMtl->GetWireSize(0)); } } else { // Material != Standard fAlpha = 1.0f; // pMaxMaterial->GetXParency(); pShaderStd->SetAmbient (ColorToVector4(pMaxMaterial->GetAmbient(), 0.0f)); pShaderStd->SetDiffuse (ColorToVector4(pMaxMaterial->GetDiffuse(), fAlpha)); pShaderStd->SetSpecular (CVector4(0.0f, 0.0f, 0.0f, 0.0f)); pShaderStd->SetShininess(0.0f); } // Layers if(!pMaxStandardMtl) { m_vecShaders.push_back(pShaderStd); continue; } bool bDiffuseMap32Bits = false; StdMat2 *pStandardMtl; for(int i = 0; i < 3; i++) { int nMap; pStandardMtl = pMaxStandardMtl; // 0 = diffuse, 1 == bump, 2 = lightmap (self illumination slot) or envmap (reflection slot) if(i == 0) { nMap = ID_DI; } else if(i == 1) { nMap = ID_BU; // If its a baked material, get the bump map from there if(pMaxBakedMtl) { pStandardMtl = pMaxBakedMtl; } } else if(i == 2) { bool bBaked = false; // If its a baked material, get the map2 (lightmap) from there if(pMaxBakedMtl) { if(pMaxBakedMtl->GetMapState(ID_SI) == MAXMAPSTATE_ENABLED) { bBaked = true; nMap = ID_SI; pStandardMtl = pMaxBakedMtl; } } if(!bBaked) { if(pStandardMtl->GetMapState(ID_SI) == MAXMAPSTATE_ENABLED) { nMap = ID_SI; } else { nMap = ID_RL; } } } // Check validity if(pStandardMtl->GetMapState(nMap) != MAXMAPSTATE_ENABLED) { if(i == 0) { LOG.Write("\n No diffuse. Skipping."); break; } continue; } Texmap* pMaxTexmap = pStandardMtl->GetSubTexmap(nMap); if(!pMaxTexmap) { if(i == 0) { LOG.Write("\n No diffuse. Skipping."); break; } continue; } // Get texmaps std::vector<std::string> vecTextures, vecPaths; CShaderStandard::SLayerInfo layerInfo; CShaderStandard::SBitmapInfo bitmapInfo; if(pMaxTexmap->ClassID() == Class_ID(BMTEX_CLASS_ID, 0)) { BitmapTex* pMaxBitmapTex = (BitmapTex*)pMaxTexmap; Bitmap* pMaxBitmap = pMaxBitmapTex->GetBitmap(SECONDS_TO_TICKS(m_fStartTime)); StdUVGen* pMaxUVGen = pMaxBitmapTex->GetUVGen(); if(!pMaxBitmap) { if(i == 0) { LOG.Write("\n Invalid diffuse. Skipping."); break; } continue; } assert(pMaxUVGen); BitmapInfo bi = pMaxBitmap->Storage()->bi; // bi.Name() returns the full path // bi.Filename() returns just the filename vecTextures.push_back(bi.Filename()); vecPaths. push_back(bi.Name()); LOG.Write("\n Bitmap %s", vecTextures[0].data()); // Check if diffuse texture has alpha channel if(i == 0) { CBitmap bitmap; CInputFile bitmapFile; if(!bitmapFile.Open(bi.Name(), false)) { CLogger::NotifyWindow("WARNING - CStravaganzaMaxTools::BuildShaders():\nUnable to load file %s", bi.Name()); } else { if(!bitmap.Load(&bitmapFile, GetFileExt(bi.Name()))) { CLogger::NotifyWindow("WARNING - CStravaganzaMaxTools::BuildShaders():\nUnable to load bitmap %s", bi.Name()); } else { if(bitmap.GetBpp() == 32) { bDiffuseMap32Bits = true; LOG.Write(" (with alpha channel)"); } bitmap.Free(); } bitmapFile.Close(); } } // Ok, copy properties layerInfo.texInfo.bLoop = false; layerInfo.texInfo.eTextureType = UtilGL::Texturing::CTexture::TEXTURE2D; bitmapInfo.strFile = m_bPreview ? bi.Name() : bi.Filename(); bitmapInfo.bTile = ((pMaxUVGen->GetTextureTiling() & (U_WRAP | V_WRAP)) == (U_WRAP | V_WRAP)) ? true : false; bitmapInfo.fSeconds = 0.0f; bitmapInfo.bForceFiltering = false; bitmapInfo.eFilter = UtilGL::Texturing::FILTER_TRILINEAR; // won't be used (forcefiltering = false) layerInfo.texInfo.m_vecBitmaps.push_back(bitmapInfo); layerInfo.eTexEnv = nMap == ID_RL ? CShaderStandard::TEXENV_ADD : CShaderStandard::TEXENV_MODULATE; layerInfo.eUVGen = pMaxUVGen->GetCoordMapping(0) == UVMAP_SPHERE_ENV ? CShaderStandard::UVGEN_ENVMAPPING : CShaderStandard::UVGEN_EXPLICITMAPPING; layerInfo.uMapChannel = pMaxUVGen->GetMapChannel(); layerInfo.v3ScrollSpeed = CVector3(0.0f, 0.0f, 0.0f); layerInfo.v3RotationSpeed = CVector3(0.0f, 0.0f, 0.0f); layerInfo.v3ScrollOffset = CVector3(pMaxUVGen->GetUOffs(0), pMaxUVGen->GetVOffs(0), 0.0f); layerInfo.v3RotationOffset = CVector3(pMaxUVGen->GetUAng(0), pMaxUVGen->GetVAng(0), pMaxUVGen->GetWAng(0)); } else if(pMaxTexmap->ClassID() == Class_ID(ACUBIC_CLASS_ID, 0)) { ACubic* pMaxCubic = (ACubic*)pMaxTexmap; IParamBlock2* pBlock = pMaxCubic->pblock; Interval validRange = m_pMaxInterface->GetAnimRange(); for(int nFace = 0; nFace < 6; nFace++) { int nMaxFace; switch(nFace) { case 0: nMaxFace = 3; break; case 1: nMaxFace = 2; break; case 2: nMaxFace = 1; break; case 3: nMaxFace = 0; break; case 4: nMaxFace = 5; break; case 5: nMaxFace = 4; break; } TCHAR *name; pBlock->GetValue(acubic_bitmap_names, TICKS_TO_SECONDS(m_fStartTime), name, validRange, nMaxFace); vecPaths.push_back(name); CStr path, file, ext; SplitFilename(CStr(name), &path, &file, &ext); std::string strFile = std::string(file.data()) + ext.data(); vecTextures.push_back(strFile); bitmapInfo.strFile = m_bPreview ? name : strFile; bitmapInfo.bTile = false; bitmapInfo.fSeconds = 0.0f; bitmapInfo.bForceFiltering = false; bitmapInfo.eFilter = UtilGL::Texturing::FILTER_TRILINEAR; layerInfo.texInfo.m_vecBitmaps.push_back(bitmapInfo); } layerInfo.texInfo.bLoop = false; layerInfo.texInfo.eTextureType = UtilGL::Texturing::CTexture::TEXTURECUBEMAP; layerInfo.eTexEnv = nMap == ID_RL ? CShaderStandard::TEXENV_ADD : CShaderStandard::TEXENV_MODULATE; layerInfo.eUVGen = CShaderStandard::UVGEN_ENVMAPPING; layerInfo.uMapChannel = 0; layerInfo.v3ScrollSpeed = CVector3(0.0f, 0.0f, 0.0f); layerInfo.v3RotationSpeed = CVector3(0.0f, 0.0f, 0.0f); layerInfo.v3ScrollOffset = CVector3(0.0f, 0.0f, 0.0f); layerInfo.v3RotationOffset = CVector3(0.0f, 0.0f, 0.0f); } else { if(i == 0) { LOG.Write("\n No diffuse. Skipping."); break; } continue; } if(!m_bPreview && m_bCopyTextures && m_strTexturePath != "") { for(int nTex = 0; nTex != vecTextures.size(); nTex++) { // Copy textures into the specified folder std::string strDestPath = m_strTexturePath; if(strDestPath[strDestPath.length() - 1] != '\\') { strDestPath.append("\\", 1); } strDestPath.append(vecTextures[nTex]); if(!CopyFile(vecPaths[nTex].data(), strDestPath.data(), FALSE)) { CLogger::NotifyWindow("Unable to copy %s to\n%s", vecPaths[i], strDestPath.data()); } } } if(layerInfo.eUVGen == CShaderStandard::UVGEN_ENVMAPPING && i == 1) { CLogger::NotifyWindow("%s : Bump with spheremapping not supported", pShaderStd->GetName().data()); } else { // Add layer switch(i) { case 0: pShaderStd->SetLayer(CShaderStandard::LAYER_DIFF, layerInfo); break; case 1: pShaderStd->SetLayer(CShaderStandard::LAYER_BUMP, layerInfo); break; case 2: pShaderStd->SetLayer(CShaderStandard::LAYER_MAP2, layerInfo); break; } } } // ¿Do we need blending? if(ARE_EQUAL(fAlpha, 1.0f) && !bDiffuseMap32Bits) { pShaderStd->SetBlendSrcFactor(UtilGL::States::BLEND_ONE); pShaderStd->SetBlendDstFactor(UtilGL::States::BLEND_ZERO); } else { pShaderStd->SetBlendSrcFactor(UtilGL::States::BLEND_SRCALPHA); pShaderStd->SetBlendDstFactor(UtilGL::States::BLEND_INVSRCALPHA); } // Add shader m_vecShaders.push_back(pShaderStd); } return true; }
void Set() { sh->Set(); sh->SetTextures(textures); }
void BlenderSync::sync_world(bool update_all) { Background *background = scene->background; Background prevbackground = *background; BL::World b_world = b_scene.world(); if(world_recalc || update_all || b_world.ptr.data != world_map) { Shader *shader = scene->default_background; ShaderGraph *graph = new ShaderGraph(); /* create nodes */ if(b_world && b_world.use_nodes() && b_world.node_tree()) { BL::ShaderNodeTree b_ntree(b_world.node_tree()); add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree); /* volume */ PointerRNA cworld = RNA_pointer_get(&b_world.ptr, "cycles"); shader->heterogeneous_volume = !get_boolean(cworld, "homogeneous_volume"); shader->volume_sampling_method = get_volume_sampling(cworld); shader->volume_interpolation_method = get_volume_interpolation(cworld); } else if(b_world) { ShaderNode *closure, *out; closure = graph->add(new BackgroundNode()); closure->input("Color")->value = get_float3(b_world.horizon_color()); out = graph->output(); graph->connect(closure->output("Background"), out->input("Surface")); } if(b_world) { /* AO */ BL::WorldLighting b_light = b_world.light_settings(); if(b_light.use_ambient_occlusion()) background->ao_factor = b_light.ao_factor(); else background->ao_factor = 0.0f; background->ao_distance = b_light.distance(); /* visibility */ PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility"); uint visibility = 0; visibility |= get_boolean(cvisibility, "camera")? PATH_RAY_CAMERA: 0; visibility |= get_boolean(cvisibility, "diffuse")? PATH_RAY_DIFFUSE: 0; visibility |= get_boolean(cvisibility, "glossy")? PATH_RAY_GLOSSY: 0; visibility |= get_boolean(cvisibility, "transmission")? PATH_RAY_TRANSMIT: 0; visibility |= get_boolean(cvisibility, "scatter")? PATH_RAY_VOLUME_SCATTER: 0; background->visibility = visibility; } else { background->ao_factor = 0.0f; background->ao_distance = FLT_MAX; } shader->set_graph(graph); shader->tag_update(scene); background->tag_update(scene); } PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles"); /* when doing preview render check for BI's transparency settings, * this is so because Blender's preview render routines are not able * to tweak all cycles's settings depending on different circumstances */ if(b_engine.is_preview() == false) background->transparent = get_boolean(cscene, "film_transparent"); else background->transparent = b_scene.render().alpha_mode() == BL::RenderSettings::alpha_mode_TRANSPARENT; background->use_shader = render_layer.use_background_shader; background->use_ao = render_layer.use_background_ao; if(background->modified(prevbackground)) background->tag_update(scene); }
TorusExample(void) : make_torus(1.0, 0.5, 36, 24) , torus_instr(make_torus.Instructions()) , torus_indices(make_torus.Indices()) , make_plane(make_plane_builders()) , plane_instr(make_plane[0].Instructions()) , plane_indices(make_plane[0].Indices()) , torus_vs(ShaderType::Vertex, ObjectDesc("Torus vertex")) , plane_vs(ShaderType::Vertex, ObjectDesc("Plane vertex")) , torus_fs(ShaderType::Fragment, ObjectDesc("Torus fragment")) , plane_fs(ShaderType::Fragment, ObjectDesc("Plane fragment")) , torus_prog(ObjectDesc("Torus")) , plane_prog(ObjectDesc("Plane")) , plane_normal(plane_prog, "Normal") , plane_camera_matrix(plane_prog, "CameraMatrix") , torus_camera_matrix(torus_prog, "CameraMatrix") , torus_model_matrix(torus_prog, "ModelMatrix") , plane(make_plane.size()) , plane_positions(make_plane.size()) { std::stringstream plane_count_def; plane_count_def <<"#define PlaneCount "<<plane.size()<<'\n'; const GLchar* torus_vs_source[3] = { "#version 330\n", plane_count_def.str().c_str(), "uniform mat4 ProjectionMatrix, ModelMatrix, CameraMatrix;" "uniform float ClipSign[PlaneCount];" "uniform vec4 ClipPlane[PlaneCount];" "in vec4 Position;" "in vec2 TexCoord;" "out vec2 vertTexCoord;" "void main(void)" "{" " vertTexCoord = TexCoord;" " gl_Position = " " ModelMatrix *" " Position;" " for(int p=0; p!=PlaneCount; ++p)" " {" " gl_ClipDistance[p] = " " ClipSign[p]* " " dot(ClipPlane[p], gl_Position);" " }" " gl_Position = " " ProjectionMatrix *" " CameraMatrix *" " gl_Position;" "}" }; torus_vs.Source(torus_vs_source, 3); torus_vs.Compile(); torus_fs.Source( "#version 330\n" "in vec2 vertTexCoord;" "out vec4 fragColor;" "void main(void)" "{" " float i = (" " int(vertTexCoord.x*36) % 2+" " int(vertTexCoord.y*24) % 2" " ) % 2;" " fragColor = vec4(1-i/2, 1-i/2, 1-i/2, 1.0);" "}" ); torus_fs.Compile(); torus_prog.AttachShader(torus_vs); torus_prog.AttachShader(torus_fs); torus_prog.Link(); torus_prog.Use(); // bind the VAO for the torus torus.Bind(); // bind the VBO for the torus vertices torus_positions.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_torus.Positions(data); // upload the data Buffer::Data(Buffer::Target::Array, data); // setup the vertex attribs array for the vertices VertexAttribArray attr(torus_prog, "Position"); attr.Setup<GLfloat>(n_per_vertex); attr.Enable(); } // bind the VBO for the torus UV-coordinates torus_texcoords.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_torus.TexCoordinates(data); // upload the data Buffer::Data(Buffer::Target::Array, data); // setup the vertex attribs array for the vertices VertexAttribArray attr(torus_prog, "TexCoord"); attr.Setup<GLfloat>(n_per_vertex); attr.Enable(); } const GLchar* plane_vs_source[3] = { "#version 330\n", plane_count_def.str().c_str(), "uniform mat4 ProjectionMatrix, CameraMatrix;" "uniform float ClipSign[PlaneCount];" "uniform vec4 ClipPlane[PlaneCount];" "uniform vec3 Normal;" "in vec4 Position;" "out vec3 vertColor;" "void main(void)" "{" " gl_Position = Position;" " for(int p=0; p!=PlaneCount; ++p)" " {" " gl_ClipDistance[p] = " " ClipSign[p]* " " dot(ClipPlane[p], gl_Position);" " }" " gl_Position = " " ProjectionMatrix *" " CameraMatrix *" " gl_Position;" " vertColor = normalize(" " abs(Normal) + " " 0.4*Position.xyz" " );" "}" }; plane_vs.Source(plane_vs_source, 3); plane_vs.Compile(); plane_fs.Source( "#version 330\n" "in vec3 vertColor;" "out vec4 fragColor;" "void main(void)" "{" " fragColor = vec4(vertColor, 0.7);" "}" ); plane_fs.Compile(); plane_prog.AttachShader(plane_vs); plane_prog.AttachShader(plane_fs); plane_prog.Link(); plane_prog.Use(); ProgramUniform<Vec4f> torus_clip_plane(torus_prog, "ClipPlane"); ProgramUniform<Vec4f> plane_clip_plane(plane_prog, "ClipPlane"); ProgramUniform<GLfloat> torus_clip_sign(torus_prog, "ClipSign"); ProgramUniform<GLfloat> plane_clip_sign(plane_prog, "ClipSign"); for(std::size_t p=0; p!=plane.size(); ++p) { plane[p].Bind(); plane_positions[p].Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n = make_plane[p].Positions(data); // upload the data Buffer::Data(Buffer::Target::Array, data); VertexAttribArray attr(plane_prog, "Position"); attr.Setup<GLfloat>(n); attr.Enable(); } { auto eq = make_plane[p].Equation(); torus_clip_plane[p].Set(eq); plane_clip_plane[p].Set(eq); } { torus_clip_signs.push_back(torus_clip_sign[p]); plane_clip_signs.push_back(plane_clip_sign[p]); } } // gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f); gl.ClearDepth(1.0f); gl.FrontFace(make_torus.FaceWinding()); gl.Enable(Capability::DepthTest); gl.BlendFunc(BlendFn::SrcAlpha, BlendFn::OneMinusSrcAlpha); }
int main(int argc, char* argv[]) { printf("Creating OpenGL context...\n"); sf::ContextSettings settings; settings.antialiasingLevel = 8; settings.majorVersion = 3; settings.minorVersion = 2; sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "DSC Demo", sf::Style::Default, settings); printf("Initializing OpenGL...\n"); glewExperimental = GL_TRUE; glewInit(); printf("VENDOR = %s\n", glGetString(GL_VENDOR)); printf("RENDERER = %s\n", glGetString(GL_RENDERER)); printf("VERSION = %s\n", glGetString(GL_VERSION)); GLuint vao; glGenVertexArrays(1, &vao); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glDepthFunc(GL_LESS); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Load/generate tet mesh based on command line argument: TetMesh * tet_mesh; printf("Generating tet mesh...\n"); /* * 1: Sphere * 2: Debug tetmesh * 3: Big debug tetmesh * 4: Collapsed tetmesh * 5: Sphere, rotated * 6: C-mesh, joining together * 7: Sphere, stretched in the x-direction */ std::string meshArg = "1"; if (argc >= 2) { meshArg = argv[1]; } if (meshArg == "2") { // Debug tetmesh tet_mesh = TetMeshFactory::create_debug_tetmesh(); printf("Evolving tet mesh ...\n"); tet_mesh->evolve(); } else if (meshArg == "3") { // Big debug tetmesh tet_mesh = TetMeshFactory::create_big_debug_tetmesh(); printf("Evolving tet mesh ...\n"); tet_mesh->evolve(); } else if (meshArg == "4") { // Collapsed tetmesh tet_mesh = TetMeshFactory::create_collapsed_tetmesh(); printf("Evolving tet mesh ...\n"); tet_mesh->evolve(); } else if (meshArg == "5") { // Rotated sphere tetmesh IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/sphere.obj"); tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh); delete mesh; for (int deg = 1; deg <= 57; deg++) { REAL angle = PI / 180; for (unsigned int i = 0; i < tet_mesh->vertices.size() / 3; i++) { if (tet_mesh->get_vertex_status(i) == INTERFACE) { glm::detail::tvec4<REAL, glm::precision::defaultp> v(tet_mesh->vertices[i*3], tet_mesh->vertices[i*3+1], tet_mesh->vertices[i*3+2], 1); glm::detail::tvec4<REAL, glm::precision::defaultp> v2 = glm::rotateX(v, angle); tet_mesh->vertex_targets[i*3] = v2[0]; tet_mesh->vertex_targets[i*3+1] = v2[1]; tet_mesh->vertex_targets[i*3+2] = v2[2]; tet_mesh->vertex_statuses[i] = MOVING; } } printf("Evolving tet mesh (%d deg)...\n", deg); tet_mesh->evolve(); } } else if (meshArg == "6") { // C-mesh IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/c_mesh.obj"); tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh); delete mesh; for (unsigned int i = 0; i < tet_mesh->vertices.size() / 3; i++) { if (tet_mesh->get_vertex_status(i) == INTERFACE) { glm::detail::tvec4<REAL, glm::precision::defaultp> v(tet_mesh->vertices[i*3], tet_mesh->vertices[i*3+1], tet_mesh->vertices[i*3+2], 1); if (tet_mesh->vertices[i*3] == 0.64f && tet_mesh->vertices[i*3+1] == 0.10f) { tet_mesh->vertex_targets[i*3] = tet_mesh->vertices[i*3]; // Stays the same tet_mesh->vertex_targets[i*3+1] = -0.10f; // Moves to create C Mesh case tet_mesh->vertex_targets[i*3+2] = tet_mesh->vertices[i*3+2]; // Stays the same } else { tet_mesh->vertex_targets[i*3] = tet_mesh->vertices[i*3]; tet_mesh->vertex_targets[i*3+1] = tet_mesh->vertices[i*3+1]; tet_mesh->vertex_targets[i*3+2] = tet_mesh->vertices[i*3+2]; } tet_mesh->vertex_statuses[i] = MOVING; } } printf("Evolving tet mesh from C mesh...\n"); tet_mesh->evolve(); } else if (meshArg == "7") { // Stretched sphere IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/sphere.obj"); tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh); for (unsigned int i = 0; i < tet_mesh->vertices.size() / 3; i++) { if (tet_mesh->get_vertex_status(i) == INTERFACE) { // scale x tet_mesh->vertex_targets[i * 3] = tet_mesh->vertices[i * 3] * 1.2; tet_mesh->vertex_targets[i * 3 + 1] = tet_mesh->vertices[i * 3 + 1]; tet_mesh->vertex_targets[i * 3 + 2] = tet_mesh->vertices[i * 3 + 2]; tet_mesh->vertex_statuses[i] = MOVING; } } printf("Evolving tet mesh ...\n"); tet_mesh->evolve(); } else { // Default case (tet mesh #1) IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/sphere.obj"); tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh); printf("Evolving tet mesh ...\n"); tet_mesh->evolve(); delete mesh; } printf("Displaying tet mesh...\n"); printf("Initializing display...\n"); Shader * shader = Shader::compile_from("shaders/dsc.vsh", "shaders/dsc.gsh", "shaders/dsc.fsh"); glUseProgram(shader->get_id()); glBindVertexArray(vao); Renderable renderable(shader, true, false, GL_TRIANGLES); tgui::Gui gui(window); gui.setGlobalFont("assets/fonts/DejaVuSans.ttf"); TetrahedralViewer viewer(&renderable, &gui); viewer.init(WINDOW_WIDTH, WINDOW_HEIGHT, FOV); viewer.bind_attributes(*tet_mesh, renderable); check_gl_error(); delete tet_mesh; printf("Starting display...\n"); sf::Event event; sf::Clock clock; tgui::Callback callback; while (window.isOpen()) { // float frame_length = clock.restart().asSeconds(); glUseProgram(shader->get_id()); glBindVertexArray(vao); while (gui.pollCallback(callback)) { viewer.handle_callback(callback); } viewer.update(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderable.render(); check_gl_error(); glUseProgram(0); glBindVertexArray(0); gui.draw(); window.display(); while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { printf("Closing window...\n"); window.close(); } viewer.handle_event(event); } sf::sleep(sf::seconds(1.0f / FRAME_RATE)); } printf("Cleaning up...\n"); delete shader; return 0; }
void ModelRenderer::render(Shader& s, RenderingEngine::RenderState) { s.bind(); tex.bind(s); mesh.Draw(); }
//---------------------------------------------------------------------------- Shader* FxCompiler::CreateShader (bool isVShader, const Program& program, InputArray& inputs, OutputArray& outputs, ConstantArray& constants, SamplerArray& samplers) { int numInputs = (int)inputs.size(); int numOutputs = (int)outputs.size(); int numConstants = (int)constants.size(); int numSamplers = (int)samplers.size(); Shader* shader; if (isVShader) { shader = new0 VertexShader(program.Name, numInputs, numOutputs, numConstants, numSamplers, true); } else { shader = new0 PixelShader(program.Name, numInputs, numOutputs, numConstants, numSamplers, true); } int i; for (i = 0; i < numInputs; ++i) { Input& input = inputs[i]; shader->SetInput(i, input.Name, input.Type, input.Semantic); } for (i = 0; i < numOutputs; ++i) { Output& output = outputs[i]; shader->SetOutput(i, output.Name, output.Type, output.Semantic); } for (i = 0; i < numConstants; ++i) { Constant& constant = constants[i]; shader->SetConstant(i, constant.Name, constant.NumRegistersUsed); shader->SetBaseRegister(mActiveProfile, i, constant.BaseRegister); } for (i = 0; i < numSamplers; ++i) { Sampler& sampler = samplers[i]; shader->SetSampler(i, sampler.Name, sampler.Type); shader->SetFilter(i, sampler.Filter); shader->SetCoordinate(i, 0, sampler.Coordinate[0]); shader->SetCoordinate(i, 1, sampler.Coordinate[1]); shader->SetCoordinate(i, 2, sampler.Coordinate[2]); shader->SetLodBias(i, sampler.LodBias); shader->SetAnisotropy(i, sampler.Anisotropy); shader->SetBorderColor(i, sampler.BorderColor); shader->SetTextureUnit(mActiveProfile, i, sampler.Unit); } shader->SetProgram(mActiveProfile, program.Text); return shader; }
void Model::draw(Shader & shader) { shader.setParameter("ModelMatrix", getMatrix()); if (m_mesh) m_mesh->draw(shader); }
ParticleSkinnedModel::ParticleSkinnedModel(Shader& pShader, Body * body, Material ** mat, unsigned int materialCount) : Model(body, mat, materialCount) { assert(body); const std::vector<Body::sTriangle> tris = m_body->getTriangleData(); std::set<Body::sConnection> uniqueConnections; // add unique line connections given by triangles for(size_t i=0; i<body->getTriangleCount(); ++i) { uniqueConnections.insert(Body::sConnection(tris[i].index[0], tris[i].index[1])); uniqueConnections.insert(Body::sConnection(tris[i].index[0], tris[i].index[2])); uniqueConnections.insert(Body::sConnection(tris[i].index[1], tris[i].index[2])); } for(std::set<Body::sConnection>::const_iterator it = uniqueConnections.begin(); it != uniqueConnections.end(); ++it) m_constraints.push_back(*it); printf("Unique connections: %zu \n", m_constraints.size()); // Find vertices that share the same positions // These must be merged after the constraints update // Or else the seems will show const float limit = 1.0e-9; const std::vector<Body::sVertex> verts = m_body->getVertexData(); for(size_t i=0; i<body->getVertexCount()-1; ++i) { for(size_t j=i+1; j<body->getVertexCount(); ++j) { glm::vec3 v = verts[i].position - verts[j].position; if(glm::dot(v,v) < limit) m_postVertexMerge.push_back(Body::sConnection(i,j)); } } printf("Post vertex merge size: %u \n", m_postVertexMerge.size()); size_t particleCount = body->getVertexCount(); m_particles.resize(particleCount); glm::vec3 boundingBoxMin(1.0e20f); glm::vec3 boundingBoxMax(-1.0e20f); for(size_t i=0; i<particleCount; ++i) { const Body::sVertex v = body->getVertexData()[i]; sParticle& p = m_particles[i]; p.position = v.position; p.oldPosition = p.position; p.mass_k_d = getParticleMass_K_D(i); boundingBoxMin = glm::min(boundingBoxMin, v.position); boundingBoxMax = glm::max(boundingBoxMax, v.position); } boundingBoxMin = boundingBoxMax - boundingBoxMin; printf("%f, %f, %f\n", boundingBoxMin.x, boundingBoxMin.y, boundingBoxMin.z); m_ps = new GPUParticleSystem(&m_particles[0], particleCount, pShader); assert(m_ps); m_particleBuffer.bind(); glBufferData(GL_ARRAY_BUFFER, particleCount * sizeof(sParticle), &m_particles[0], GL_STREAM_DRAW); m_particleBuffer.unbind(); int positionAttr = pShader.getAttribLocation("in_vertexPosition"); int weightAttr = pShader.getAttribLocation("in_vertexWeight"); printf("positionAttr %i\n", positionAttr); printf("weightAttr %i\n", weightAttr); const char * pOffset = 0; // Append Vertex Attribute pointers to the particle systems VAOs glBindVertexArray(m_ps->getSourceVA()); glBindBuffer(GL_ARRAY_BUFFER, body->getVertexBuffer()); glEnableVertexAttribArray(positionAttr); glEnableVertexAttribArray(weightAttr); glVertexAttribPointer(positionAttr, 3, GL_FLOAT, GL_FALSE, sizeof(Body::sVertex), pOffset); glVertexAttribPointer(weightAttr, 4, Body::VertexWeight::getGLType(), GL_FALSE, sizeof(Body::sVertex), 32 + pOffset); glBindVertexArray(0); glBindVertexArray(m_ps->getTargetVA()); glBindBuffer(GL_ARRAY_BUFFER, body->getVertexBuffer()); glEnableVertexAttribArray(positionAttr); glEnableVertexAttribArray(weightAttr); glVertexAttribPointer(positionAttr, 3, GL_FLOAT, GL_FALSE, sizeof(Body::sVertex), pOffset); glVertexAttribPointer(weightAttr, 4, Body::VertexWeight::getGLType(), GL_FALSE, sizeof(Body::sVertex), 32 + pOffset); glBindVertexArray(0); }
void Image::encodeGpu (EncoderGpu *encoder) { //Prepare image data for encoding updateFlat(); updateBounds(); updateBuffers(); glViewport( 0, 0, gridSize.x, gridSize.y ); glDisable( GL_DEPTH_TEST ); glDisable( GL_MULTISAMPLE ); ///////////////////////////////////////////////////// // Init size counters and main grid { Shader *shader = encoder->shaderInit; shader->use(); Int32 uPtrInfo = shader->program->getUniform( "ptrInfo" ); glUniformui64( uPtrInfo, bufGpuInfo.getAddress() ); Int32 uPtrGrid = shader->program->getUniform( "ptrGrid" ); glUniformui64( uPtrGrid, bufGpuGrid.getAddress() ); Int32 uGridSize = shader->program->getUniform( "gridSize" ); glUniform2i( uGridSize, gridSize.x, gridSize.y ); renderFullScreenQuad( shader ); } ///////////////////////////////////////////////////// // Init object grids { Shader *shader = encoder->shaderInitObject; shader->use(); Int32 uPtrObjects = shader->program->getUniform( "ptrObjects" ); glUniformui64( uPtrObjects, bufObjInfos.getAddress() ); Int32 uPtrGrid = shader->program->getUniform( "ptrGrid" ); glUniformui64( uPtrGrid, bufGpuGrid.getAddress() ); Int32 uGridOrigin = shader->program->getUniform( "gridOrigin" ); glUniform2f( uGridOrigin, gridOrigin.x, gridOrigin.y ); Int32 uGridSize = shader->program->getUniform( "gridSize" ); glUniform2i( uGridSize, gridSize.x, gridSize.y ); Int32 uCellSize = shader->program->getUniform( "cellSize" ); glUniform2f( uCellSize, cellSize.x, cellSize.y ); Int32 aPos = shader->program->getAttribute( "in_pos" ); glBindBuffer( GL_ARRAY_BUFFER, bufObjs.getId() ); glVertexAttribPointer( aPos, 3, GL_FLOAT, false, sizeof(vec3), 0 ); glEnableVertexAttribArray( aPos ); glDrawArrays( GL_LINES, 0, objs.size() * 2 ); glDisableVertexAttribArray( aPos ); } glMemoryBarrier( GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV ); checkGlError( "encodeImage init" ); ///////////////////////////////////////////////////// // Encode object lines { Shader *shader = encoder->shaderLines; shader->use(); Int32 uPtrObjects = shader->program->getUniform( "ptrObjects" ); glUniformui64( uPtrObjects, bufObjInfos.getAddress() ); Int32 uPtrInfo = shader->program->getUniform( "ptrInfo" ); glUniformui64( uPtrInfo, bufGpuInfo.getAddress() ); Int32 uPtrGrid = shader->program->getUniform( "ptrGrid" ); glUniformui64( uPtrGrid, bufGpuGrid.getAddress() ); Int32 uPtrStream = shader->program->getUniform( "ptrStream" ); glUniformui64( uPtrStream, bufGpuStream.getAddress() ); Int32 uGridOrigin = shader->program->getUniform( "gridOrigin" ); glUniform2f( uGridOrigin, gridOrigin.x, gridOrigin.y ); Int32 uGridSize = shader->program->getUniform( "gridSize" ); glUniform2i( uGridSize, gridSize.x, gridSize.y ); Int32 uCellSize = shader->program->getUniform( "cellSize" ); glUniform2f( uCellSize, cellSize.x, cellSize.y ); for (int o=0; o<(int)objects.size(); ++o) { Object *object = objects[o]; Int32 uObjectId = shader->program->getUniform( "objectId" ); glUniform1i( uObjectId, o ); Int32 aPos = shader->program->getAttribute( "in_pos" ); glBindBuffer( GL_ARRAY_BUFFER, object->bufLines.getId() ); glVertexAttribPointer( aPos, 2, GL_FLOAT, false, sizeof( Vec2 ), 0 ); glEnableVertexAttribArray( aPos ); glDrawArrays( GL_LINES, 0, object->lines.size() * 2 ); glDisableVertexAttribArray( aPos ); } } ///////////////////////////////////////////////////// // Encode object quads { Shader *shader = encoder->shaderQuads; shader->use(); Int32 uPtrObjects = shader->program->getUniform( "ptrObjects" ); glUniformui64( uPtrObjects, bufObjInfos.getAddress() ); Int32 uPtrInfo = shader->program->getUniform( "ptrInfo" ); glUniformui64( uPtrInfo, bufGpuInfo.getAddress() ); Int32 uPtrGrid = shader->program->getUniform( "ptrGrid" ); glUniformui64( uPtrGrid, bufGpuGrid.getAddress() ); Int32 uPtrStream = shader->program->getUniform( "ptrStream" ); glUniformui64( uPtrStream, bufGpuStream.getAddress() ); Int32 uGridOrigin = shader->program->getUniform( "gridOrigin" ); glUniform2f( uGridOrigin, gridOrigin.x, gridOrigin.y ); Int32 uGridSize = shader->program->getUniform( "gridSize" ); glUniform2i( uGridSize, gridSize.x, gridSize.y ); Int32 uCellSize = shader->program->getUniform( "cellSize" ); glUniform2f( uCellSize, cellSize.x, cellSize.y ); for (int o=0; o<(int)objects.size(); ++o) { Object *object = objects[o]; Int32 uObjectId = shader->program->getUniform( "objectId" ); glUniform1i( uObjectId, o ); Int32 aPos = shader->program->getAttribute( "in_pos" ); glBindBuffer( GL_ARRAY_BUFFER, object->bufQuads.getId() ); glVertexAttribPointer( aPos, 2, GL_FLOAT, false, sizeof( Vec2 ), 0 ); glEnableVertexAttribArray( aPos ); glDrawArrays( GL_TRIANGLES, 0, object->quads.size() * 3 ); glDisableVertexAttribArray( aPos ); } } glMemoryBarrier( GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV ); checkGlError( "encodeImage lines quads" ); ///////////////////////////////////////////////////// // Encode object properties { Shader *shader = encoder->shaderObject; shader->use(); Int32 uPtrObjects = shader->program->getUniform( "ptrObjects" ); glUniformui64( uPtrObjects, bufObjInfos.getAddress() ); Int32 uPtrInfo = shader->program->getUniform( "ptrInfo" ); glUniformui64( uPtrInfo, bufGpuInfo.getAddress() ); Int32 uPtrGrid = shader->program->getUniform( "ptrGrid" ); glUniformui64( uPtrGrid, bufGpuGrid.getAddress() ); Int32 uPtrStream = shader->program->getUniform( "ptrStream" ); glUniformui64( uPtrStream, bufGpuStream.getAddress() ); Int32 uGridOrigin = shader->program->getUniform( "gridOrigin" ); glUniform2f( uGridOrigin, gridOrigin.x, gridOrigin.y ); Int32 uGridSize = shader->program->getUniform( "gridSize" ); glUniform2i( uGridSize, gridSize.x, gridSize.y ); Int32 uCellSize = shader->program->getUniform( "cellSize" ); glUniform2f( uCellSize, cellSize.x, cellSize.y ); for (int o=0; o<(int)objects.size(); ++o) { Object *object = objects[o]; ObjInfo &obj = objInfos[o]; // Int32 uPtrObjGrid = shader->program->getUniform( "ptrObjGrid" ); glUniformui64( uPtrObjGrid, bufGpuGrid.getAddress() + obj.gridOffset * sizeof(int) ); Int32 uObjGridOrigin = shader->program->getUniform( "objGridOrigin" ); glUniform2i( uObjGridOrigin, obj.gridOrigin.x, obj.gridOrigin.y ); Int32 uObjGridSize = shader->program->getUniform( "objGridSize" ); glUniform2i( uObjGridSize, obj.gridSize.x, obj.gridSize.y ); // Int32 uObjectId = shader->program->getUniform( "objectId" ); glUniform1i( uObjectId, o ); Int32 uColor = shader->program->getUniform( "color" ); glUniform4fv( uColor, 1, (GLfloat*) &object->color ); //Transform and round object bounds to grid space Vec2 min = Vec::Floor( (object->min - gridOrigin) / cellSize ); Vec2 max = Vec::Ceil( (object->max - gridOrigin) / cellSize ); //Transform to [-1,1] normalized coordinates (glViewport will transform back) min = (min / vec2( gridSize )) * 2.0f - Vec2(1.0f,1.0f); max = (max / vec2( gridSize )) * 2.0f - Vec2(1.0f,1.0f); renderQuad( shader, min, max ); } } glMemoryBarrier( GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV ); checkGlError( "encodeImage object" ); ///////////////////////////////////////////////////// // Sort objects in every cell back to front { Shader *shader = encoder->shaderSort; shader->use(); Int32 uPtrGrid = shader->program->getUniform( "ptrGrid" ); glUniformui64( uPtrGrid, bufGpuGrid.getAddress() ); Int32 uPtrStream = shader->program->getUniform( "ptrStream" ); glUniformui64( uPtrStream, bufGpuStream.getAddress() ); Int32 uGridSize = shader->program->getUniform( "gridSize" ); glUniform2i( uGridSize, gridSize.x, gridSize.y ); renderFullScreenQuad( shader ); } glMemoryBarrier( GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV ); checkGlError( "encodeImage sort" ); }
void Renderer::_renderSpriteBatch(glm::mat4& modelMatrix, std::vector<Sprite*>& spritebatch, Camera* camera) { Sprite* spr = spritebatch[0]; Shader* shader = _uberShader; // ask resourcemanager if (shader == NULL) { shader = _resman.getShader(spr->vertexshader().c_str(), spr->fragmentshader().c_str()); } std::string texturename = spr->texturename(); int filter = spr->filter(); int wrap = spr->wrap(); Texture* texture = _resman.getTexture(texturename, filter, wrap); if (spr->size.x == 0) { spr->size.x = texture->width() * spr->uvdim.x; } if (spr->size.y == 0) { spr->size.y = texture->height() * spr->uvdim.y; } Mesh* mesh = _resman.getSpriteMesh(spr->size.x, spr->size.y, spr->pivot.x, spr->pivot.y, spr->uvdim.x, spr->uvdim.y, spr->circlemesh(), spr->which()); if (texture != NULL) { // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture->getGLTexture()); // for every Sprite in the batch... int s = spritebatch.size(); for (int i = 0; i < s; i++) { Sprite* sprite = spritebatch[i]; // a Sprite handle int culled = 0; // state that we need to draw it if (sprite->useCulling()) { // but maybe we don't int half_width = SWIDTH/2; int half_height = SHEIGHT/2; int left_edge = camera->position.x - half_width; int right_edge = camera->position.x + half_width; int top_edge = camera->position.y - half_height; int bottom_edge = camera->position.y + half_height; float posx = sprite->spriteposition.x; float posy = sprite->spriteposition.y; int debug = 0; if (debug) { // cull visibly within the frame if (posx - spr->size.x < left_edge) { culled = 1; } if (posx + spr->size.x > right_edge) { culled = 1; } if (posy + spr->size.y > bottom_edge) { culled = 1; } if (posy - spr->size.y < top_edge) { culled = 1; } } else { if (posx + spr->size.x < left_edge) { culled = 1; } if (posx - spr->size.x > right_edge) { culled = 1; } if (posy - spr->size.y > bottom_edge) { culled = 1; } if (posy + spr->size.y < top_edge) { culled = 1; } } } // this Sprite isn't culled and needs to be drawn if (!culled) { RGBAColor blendcolor = sprite->color; // _uvOffsetID glUniform2f(shader->uvOffsetID(), sprite->uvoffset.x, sprite->uvoffset.y); // use spritepos for position glm::vec3 position = glm::vec3(sprite->spriteposition.x, sprite->spriteposition.y, 0.0f); glm::vec3 rotation = glm::vec3(0.0f, 0.0f, sprite->spriterotation); glm::vec3 scale = glm::vec3(sprite->spritescale.x, sprite->spritescale.y, 0.0f); // Build the Model matrix glm::mat4 translationMatrix = glm::translate(modelMatrix, position); glm::mat4 rotationMatrix = glm::eulerAngleYXZ(0.0f, 0.0f, rotation.z); glm::mat4 scalingMatrix = glm::scale(glm::mat4(1.0f), scale); glm::mat4 mm = translationMatrix * rotationMatrix * scalingMatrix; this->_renderMesh(mm, shader, texture, mesh, mesh->numverts(), GL_TRIANGLES, blendcolor); } } } }
void MapViewer::render_objects(bool above_sprite) { //Calculate the projection matrix std::pair<int, int> size = window->get_size(); glm::mat4 projection_matrix = glm::ortho(0.0f, float(size.first), 0.0f, float(size.second), 0.0f, 1.0f); //Draw the objects const std::vector<int>& objects = map->get_map_objects(); ObjectManager& object_manager = ObjectManager::get_instance(); for(auto it = objects.begin(); it != objects.end(); ++it) { if(*it != 0) { std::shared_ptr<MapObject> object = object_manager.get_object<MapObject>(*it); if(!object) continue; //If we can't render the object if(!object->is_renderable()) continue; if(above_sprite ^ object->render_above_sprites()) continue; RenderableComponent* object_render_component = object->get_renderable_component(); //Move object to the required position glm::vec3 translator( object->get_position().x - get_display_x(), object->get_position().y - get_display_y(), 0.0f ); glm::mat4 model(glm::mat4(1.0f)); model = glm::scale (model, glm::vec3(Engine::get_actual_tile_size())); model = glm::translate(model, translator); object_render_component->set_modelview_matrix(model); object_render_component->set_projection_matrix(projection_matrix); object_render_component->bind_shader(); Shader* shader = object_render_component->get_shader().get(); if(shader == nullptr) { LOG(ERROR) << "MapViewer::render_map: Shader (object_render_component->get_shader()) should not be null"; return; } // TODO: I don't want to actually expose the shader, put these into wrappers in the shader object GLuint mat_projection(glGetUniformLocation(shader->get_program(), "mat_projection")); glUniformMatrix4fv(mat_projection, 1, GL_FALSE, glm::value_ptr(object_render_component->get_projection_matrix())); GLuint mat_modelview(glGetUniformLocation(shader->get_program(), "mat_modelview")); glUniformMatrix4fv(mat_modelview, 1, GL_FALSE, glm::value_ptr(object_render_component->get_modelview_matrix())); object_render_component->bind_vbos(); object_render_component->bind_textures(); glDrawArrays(GL_TRIANGLES, 0, object_render_component->get_num_vertices_render()); object_render_component->release_textures(); object_render_component->release_vbos(); object_render_component->release_shader(); } } }
/** * @brief Renders the trackball representation. * @todo setTrackballOrthographicMatrix should be set during viewport resize */ void render (void) { if(drawTrackball) { float ratio = (viewport[2] - viewport[0]) / (viewport[3] - viewport[1]); setTrackballOrthographicMatrix(-ratio, ratio, -1.0, 1.0, 0.1, 100.0); trackball_shader.bind(); //Using unique viewMatrix for the trackball, considering only the rotation to be visualized. Eigen::Affine3f trackballViewMatrix = Eigen::Affine3f::Identity(); trackballViewMatrix.translate(defaultTranslation); trackballViewMatrix.rotate(quaternion); trackball_shader.setUniform("viewMatrix", trackballViewMatrix); trackball_shader.setUniform("projectionMatrix", trackballProjectionMatrix); trackball_shader.setUniform("nearPlane", near_plane); trackball_shader.setUniform("farPlane", far_plane); bindBuffers(); //X: Eigen::Vector4f colorVector(1.0, 0.0, 0.0, 1.0); trackball_shader.setUniform("modelMatrix", Eigen::Affine3f::Identity()*Eigen::AngleAxis<float>(M_PI/2.0,Eigen::Vector3f(0.0,1.0,0.0))); trackball_shader.setUniform("in_Color", colorVector); glDrawArrays(GL_LINE_LOOP, 0, 200); //Y: colorVector << 0.0, 1.0, 0.0, 1.0; trackball_shader.setUniform("modelMatrix", Eigen::Affine3f::Identity()*Eigen::AngleAxis<float>(M_PI/2.0,Eigen::Vector3f(1.0,0.0,0.0))); trackball_shader.setUniform("in_Color", colorVector); glDrawArrays(GL_LINE_LOOP, 0, 200); //Z: colorVector << 0.0, 0.0, 1.0, 1.0; trackball_shader.setUniform("modelMatrix", Eigen::Affine3f::Identity()); trackball_shader.setUniform("in_Color", colorVector); glDrawArrays(GL_LINE_LOOP, 0, 200); unbindBuffers(); trackball_shader.unbind(); } }
int main(int argc, char **argv) { Config cfg = readConfig(); // Misc.cpp Scene_SDL* CurrentScene = new Scene_SDL(cfg.ResolutionX,cfg.ResolutionY); vec2 resolution = vec2(cfg.ResolutionX, cfg.ResolutionY); Vao vaoA = Vao("Mesh/thing.obj"); vaoA.load(vec4(0,0,0,0)); Vao vaoB = Vao("Mesh/plane.obj"); vaoB.load(vec4(0, 0, 0, 0)); TextureCfg texCfgA = { GL_RGB8, GL_NEAREST, GL_REPEAT }; Texture texA = Texture("Texture/checker.png", texCfgA); texA.load(); Shader shaderForward = Shader("Shader/test.vert", "Shader/test.frag"); shaderForward.load(); Shader shaderGeometry = Shader("Shader/defPass1.vert", "Shader/defPass1.frag"); shaderGeometry.load(); Shader shaderDeferred = Shader("Shader/defPassN.vert", "Shader/defPassN.frag"); shaderDeferred.load(); Shader shaderDeferredDebug = Shader("Shader/defPassN.vert", "Shader/defPassNDebug.frag"); shaderDeferredDebug.load(); Shader* shaderSelected = &shaderDeferred; Shader shaderAO = Shader("Shader/defPassN.vert", "Shader/AO.frag"); shaderAO.load(); Fbo* fboGeometry = createFboGeometry(cfg); // Misc.cpp Fbo* fboAO = createFbo_1ch(cfg); Vao2D supportFbo = Vao2D(); supportFbo.load(); glm::mat4 projection; glm::mat4 modelview; glm::mat4 view; projection = glm::perspective(70.0*M_PI/180.0, (double)cfg.ResolutionX / (double)cfg.ResolutionY, 0.01, 100.0); view = glm::lookAt(glm::vec3(2,2,2), glm::vec3(0, 0, 0.5), glm::vec3(0, 0, 1)); GLuint mAttach[3] = { GL_COLOR_ATTACHMENT0 , GL_COLOR_ATTACHMENT1 ,GL_COLOR_ATTACHMENT2 }; Input input; int frame = 0; while (!input.end()) { frame++; input.update(); if (input.getRisingKey(SDL_SCANCODE_SPACE)) { shaderSelected = (shaderSelected == &shaderDeferredDebug) ? &shaderDeferred : &shaderDeferredDebug; } glViewport(0, 0, cfg.ResolutionX, cfg.ResolutionY); glBindFramebuffer(GL_FRAMEBUFFER, fboGeometry->getId()); glDrawBuffers(3, mAttach); glDisable(GL_BLEND); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(shaderGeometry.getProgramID()); glUniformMatrix4fv(glGetUniformLocation(shaderGeometry.getProgramID(), "projection"), 1, GL_FALSE, value_ptr(projection)); glUniform2fv(glGetUniformLocation(shaderGeometry.getProgramID(), "resolution"), 1, value_ptr(resolution)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texA.getId()); glUniform1i(glGetUniformLocation(shaderGeometry.getProgramID(), "texture_diffuse"), 0); modelview = rotate(view, (input.getX() - cfg.ResolutionX) / 200.0f, vec3(0.0f, 0.0f, 1.0f)); modelview = translate(modelview, vec3(0, 0, 0.8)); glUniformMatrix4fv(glGetUniformLocation(shaderGeometry.getProgramID(), "modelview"), 1, GL_FALSE, value_ptr(modelview)); glUniformMatrix3fv(glGetUniformLocation(shaderGeometry.getProgramID(), "normal"), 1, GL_FALSE, value_ptr(transpose(inverse(glm::mat3(modelview))))); vaoA.draw(); modelview = view; glUniformMatrix4fv(glGetUniformLocation(shaderGeometry.getProgramID(), "modelview"), 1, GL_FALSE, value_ptr(modelview)); glUniformMatrix3fv(glGetUniformLocation(shaderGeometry.getProgramID(), "normal"), 1, GL_FALSE, value_ptr(transpose(inverse(glm::mat3(modelview))))); vaoB.draw(); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_BLEND); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(shaderSelected->getProgramID()); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, fboGeometry->getColorBufferId(0)); glUniform1i(glGetUniformLocation(shaderSelected->getProgramID(), "gNormal"), 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, fboGeometry->getColorBufferId(1)); glUniform1i(glGetUniformLocation(shaderSelected->getProgramID(), "gDiffuse"), 1); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, fboGeometry->getColorBufferId(2)); glUniform1i(glGetUniformLocation(shaderSelected->getProgramID(), "gPosition"), 2); glUniformMatrix4fv(glGetUniformLocation(shaderSelected->getProgramID(), "projection"), 1, GL_FALSE, value_ptr(projection)); glUniform1f(glGetUniformLocation(shaderSelected->getProgramID(), "varA"), input.getY() / resolution.y); glUniform1i(glGetUniformLocation(shaderSelected->getProgramID(), "time"), frame); glUniform2fv(glGetUniformLocation(shaderSelected->getProgramID(), "resolution"), 1, value_ptr(resolution)); supportFbo.draw(); CurrentScene->flip(); } delete CurrentScene; return 0; }
ShaderProgram::ShaderProgram(Shader &vert, Shader &frag) : m_VertShader(vert.ID()), m_FragShader(frag.ID()) { CreateProgram(); }
ShadowVolExample(const ExampleParams& params) : shape_instr(make_shape.Instructions()) , shape_indices(make_shape.Indices()) , shape_vs(ShaderType::Vertex, ObjectDesc("Shape vertex")) , depth_vs(ShaderType::Vertex, ObjectDesc("Depth vertex")) , light_vs(ShaderType::Vertex, ObjectDesc("Light vertex")) , depth_gs(ShaderType::Geometry, ObjectDesc("Depth geometry")) , light_gs(ShaderType::Geometry, ObjectDesc("Light geometry")) , shape_fs(ShaderType::Fragment, ObjectDesc("Shape fragment")) , depth_fs(ShaderType::Fragment, ObjectDesc("Depthfragment")) , light_fs(ShaderType::Fragment, ObjectDesc("Light fragment")) , shape_prog(ObjectDesc("Shape")) , depth_prog(ObjectDesc("Depth")) , light_prog(ObjectDesc("Light")) , tex_side(128) , sample_count(params.HighQuality()?1024:128) { shape_vs.Source( "#version 330\n" "uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;" "in vec4 Position;" "in vec3 Normal;" "in vec2 TexCoord;" "out vec3 vertNormal;" "out vec3 vertLightDir;" "out vec3 vertLightRefl;" "out vec3 vertViewDir;" "out vec3 vertViewRefl;" "uniform vec3 LightPos;" "void main(void)" "{" " gl_Position = ModelMatrix * Position;" " vertNormal = mat3(ModelMatrix)*Normal;" " vertLightDir = LightPos - gl_Position.xyz;" " vertLightRefl = reflect(" " -normalize(vertLightDir)," " normalize(vertNormal)" " );" " vertViewDir = (vec4(0.0, 0.0, 1.0, 1.0)* CameraMatrix).xyz;" " vertViewRefl = reflect(" " normalize(vertViewDir)," " normalize(vertNormal)" " );" " gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;" "}" ); shape_vs.Compile(); shape_fs.Source( "#version 330\n" "in vec3 vertNormal;" "in vec3 vertLightDir;" "in vec3 vertLightRefl;" "in vec3 vertViewDir;" "in vec3 vertViewRefl;" "out vec4 fragColor;" "void main(void)" "{" " float l = length(vertLightDir);" " float d = dot(" " normalize(vertNormal), " " normalize(vertLightDir)" " ) / l;" " float s = dot(" " normalize(vertLightRefl)," " normalize(vertViewDir)" " );" " vec3 ambi = vec3(0.6, 0.3, 0.5);" " vec3 diff = vec3(0.9, 0.7, 0.8);" " vec3 spec = vec3(1.0, 0.9, 0.95);" " fragColor = vec4(" " ambi * 0.3 + " " diff * 0.7 * max(d, 0.0) + " " spec * pow(max(s, 0.0), 64), " " 1.0" " );" "}" ); shape_fs.Compile(); shape_prog.AttachShader(shape_vs); shape_prog.AttachShader(shape_fs); shape_prog.Link(); depth_vs.Source( "#version 330\n" "uniform mat4 ModelMatrix;" "uniform vec3 LightPos;" "in vec4 Position;" "void main(void)" "{" " gl_Position = " " mat4(" " 1.0, 0.0, 0.0, -LightPos.x," " 0.0, 1.0, 0.0, -LightPos.y," " 0.0, 0.0, 1.0, -LightPos.z," " 0.0, 0.0, 0.0, 1.0" " )*" " ModelMatrix *" " mat4(" " 10.0, 0.0, 0.0, 0.0," " 0.0, 10.0, 0.0, 0.0," " 0.0, 0.0, 10.0, 0.0," " 0.0, 0.0, 0.0, 1.0 " " )*" " Position;" "}" ); depth_vs.Compile(); depth_gs.Source( "#version 330\n" "layout(triangles) in;" "layout(triangle_strip, max_vertices = 18) out;" "uniform mat4 ProjectionMatrix;" "const mat4 CubeFaceMatrix[6] = mat4[6](" " mat4(" " 0.0, 0.0, -1.0, 0.0," " 0.0, -1.0, 0.0, 0.0," " -1.0, 0.0, 0.0, 0.0," " 0.0, 0.0, 0.0, 1.0 " " ), mat4(" " 0.0, 0.0, 1.0, 0.0," " 0.0, -1.0, 0.0, 0.0," " 1.0, 0.0, 0.0, 0.0," " 0.0, 0.0, 0.0, 1.0 " " ), mat4(" " 1.0, 0.0, 0.0, 0.0," " 0.0, 0.0, -1.0, 0.0," " 0.0, 1.0, 0.0, 0.0," " 0.0, 0.0, 0.0, 1.0 " " ), mat4(" " 1.0, 0.0, 0.0, 0.0," " 0.0, 0.0, 1.0, 0.0," " 0.0, -1.0, 0.0, 0.0," " 0.0, 0.0, 0.0, 1.0 " " ), mat4(" " 1.0, 0.0, 0.0, 0.0," " 0.0, -1.0, 0.0, 0.0," " 0.0, 0.0, -1.0, 0.0," " 0.0, 0.0, 0.0, 1.0 " " ), mat4(" " -1.0, 0.0, 0.0, 0.0," " 0.0, -1.0, 0.0, 0.0," " 0.0, 0.0, 1.0, 0.0," " 0.0, 0.0, 0.0, 1.0 " " )" ");" "void main(void)" "{" " for(gl_Layer=0; gl_Layer!=6; ++gl_Layer)" " {" " for(int i=0; i!=3; ++i)" " {" " gl_Position = " " ProjectionMatrix *" " CubeFaceMatrix[gl_Layer]*" " gl_in[i].gl_Position;" " EmitVertex();" " }" " EndPrimitive();" " }" "}" ); depth_gs.Compile(); depth_fs.Source( "#version 330\n" "void main(void)" "{" " gl_FragDepth = gl_FragCoord.z;" "}" ); depth_fs.Compile(); depth_prog.AttachShader(depth_vs); depth_prog.AttachShader(depth_gs); depth_prog.AttachShader(depth_fs); depth_prog.Link(); depth_prog.Use(); Uniform<Mat4f>(depth_prog, "ProjectionMatrix").Set( CamMatrixf::PerspectiveX( RightAngles(1.0), 1.0, 0.1, 10.0 ) ); // bind the VAO for the shape shape.Bind(); shape_positions.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_shape.Positions(data); Buffer::Data(Buffer::Target::Array, data); VertexAttribSlot location; if(VertexAttribArray::QueryCommonLocation( "Position", location, shape_prog, depth_prog )) { VertexAttribArray shape_attr(location); shape_attr.Setup(n_per_vertex, DataType::Float); shape_attr.Enable(); } else assert(!"Inconsistent 'Position' location"); } shape_normals.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_shape.Normals(data); Buffer::Data(Buffer::Target::Array, data); shape_prog.Use(); VertexAttribArray attr(shape_prog, "Normal"); attr.Setup(n_per_vertex, DataType::Float); attr.Enable(); } light_vs.Source( "#version 330\n" "in vec3 Position;" "out float vertZOffs;" "uniform vec3 LightPos;" "uniform int SampleCount;" "void main(void)" "{" " float hp = (SampleCount-1) * 0.5;" " vertZOffs = (gl_InstanceID - hp)/hp;" " gl_Position = vec4(Position + LightPos, 1.0);" "}" ); light_vs.Compile(); light_gs.Source( "#version 330\n" "layout(points) in;" "layout(triangle_strip, max_vertices = 4) out;" "in float vertZOffs[];" "out vec4 geomPosition;" "uniform mat4 CameraMatrix, ProjectionMatrix;" "uniform vec3 ViewX, ViewY, ViewZ;" "uniform float LightVolSize;" "void main(void)" "{" " float zo = vertZOffs[0];" " float yo[2] = float[2](-1.0, 1.0);" " float xo[2] = float[2](-1.0, 1.0);" " for(int j=0;j!=2;++j)" " for(int i=0;i!=2;++i)" " {" " geomPosition = vec4(" " gl_in[0].gl_Position.xyz+" " ViewX * xo[i] * LightVolSize+" " ViewY * yo[j] * LightVolSize+" " ViewZ * zo * LightVolSize," " 1.0" " );" " gl_Position = " " ProjectionMatrix *" " CameraMatrix *" " geomPosition;" " EmitVertex();" " }" " EndPrimitive();" "}" ); light_gs.Compile(); light_fs.Source( "#version 330\n" "in vec4 geomPosition;" "out vec4 fragColor;" "uniform samplerCubeShadow ShadowMap;" "uniform int SampleCount;" "uniform vec3 LightPos;" "void main(void)" "{" " vec3 LightDir = geomPosition.xyz - LightPos;" " vec4 ShadowCoord = vec4(" " normalize(LightDir)," " length(LightDir)" " );" " float s = texture(ShadowMap, ShadowCoord);" " float alpha = s / (SampleCount * pow(length(LightDir), 2));" " fragColor = vec4(1.0, 1.0, 1.0, alpha);" "}" ); light_fs.Compile(); light_prog.AttachShader(light_vs); light_prog.AttachShader(light_gs); light_prog.AttachShader(light_fs); light_prog.Link(); light_prog.Use(); // bind the VAO for the light volume light.Bind(); // bind the VBO for the light volume plane positions light_positions.Bind(Buffer::Target::Array); { GLfloat position[3] = {0.0, 0.0, 0.0}; Buffer::Data(Buffer::Target::Array, 3, position); VertexAttribArray attr(light_prog, "Position"); attr.Setup(3, DataType::Float); attr.Enable(); } Uniform<GLint>(light_prog, "SampleCount").Set(sample_count); Uniform<GLfloat>(light_prog, "LightVolSize").Set(4); UniformSampler(light_prog, "ShadowMap").Set(0); // Setup the texture and the offscreen FBO Texture::Active(0); { auto bound_tex = Bind(depth_tex, Texture::Target::CubeMap); bound_tex.MinFilter(TextureMinFilter::Linear); bound_tex.MagFilter(TextureMagFilter::Linear); bound_tex.WrapS(TextureWrap::ClampToEdge); bound_tex.WrapT(TextureWrap::ClampToEdge); bound_tex.WrapR(TextureWrap::ClampToEdge); bound_tex.CompareFunc(CompareFunction::LEqual); bound_tex.CompareMode( TextureCompareMode::CompareRefToTexture ); for(int i=0; i!=6; ++i) { Texture::Image2D( Texture::CubeMapFace(i), 0, PixelDataInternalFormat::DepthComponent, tex_side, tex_side, 0, PixelDataFormat::DepthComponent, PixelDataType::Float, nullptr ); } auto bound_fbo = Bind( depth_fbo, Framebuffer::Target::Draw ); bound_fbo.AttachTexture( FramebufferAttachment::Depth, depth_tex, 0 ); } // gl.ClearColor(0.2f, 0.05f, 0.1f, 0.0f); gl.ClearDepth(1.0f); gl.Enable(Capability::DepthTest); gl.Enable(Capability::CullFace); gl.FrontFace(make_shape.FaceWinding()); gl.CullFace(Face::Back); gl.BlendFunc(BlendFunction::SrcAlpha, BlendFunction::One); }
bool DeferredRenderTechnique::Initialize() { const char vertexSource_Basic[] = "#version 140\n" "in vec3 VertexPosition;\n" "uniform mat4 WorldViewProjMatrix;\n" "void main()\n" "{\n" "gl_Position = WorldViewProjMatrix * vec4(VertexPosition, 1.0);\n" "}\n"; const char vertexSource_PostProcess[] = "#version 140\n" "in vec3 VertexPosition;\n" "void main()\n" "{\n" "gl_Position = vec4(VertexPosition, 1.0);" "}\n"; ShaderStage basicVertexStage(ShaderStageType_Vertex); if (!basicVertexStage.IsValid()) { NazaraError("Failed to create basic vertex shader"); return false; } basicVertexStage.SetSource(vertexSource_Basic, sizeof(vertexSource_Basic)); if (!basicVertexStage.Compile()) { NazaraError("Failed to compile basic vertex shader"); return false; } ShaderStage ppVertexStage(ShaderStageType_Vertex); if (!ppVertexStage.IsValid()) { NazaraError("Failed to create vertex shader"); return false; } ppVertexStage.SetSource(vertexSource_PostProcess, sizeof(vertexSource_PostProcess)); if (!ppVertexStage.Compile()) { NazaraError("Failed to compile vertex shader"); return false; } String error; Shader* shader; // Shaders critiques (Nécessaires pour le Deferred Shading minimal) shader = RegisterDeferredShader("DeferredGBufferClear", r_fragmentSource_GBufferClear, sizeof(r_fragmentSource_GBufferClear), ppVertexStage, &error); if (!shader) { NazaraError("Failed to register critical shader: " + error); return false; } shader = RegisterDeferredShader("DeferredDirectionnalLight", r_fragmentSource_DirectionalLight, sizeof(r_fragmentSource_DirectionalLight), ppVertexStage, &error); if (!shader) { NazaraError("Failed to register critical shader: " + error); return false; } shader->SendInteger(shader->GetUniformLocation("GBuffer0"), 0); shader->SendInteger(shader->GetUniformLocation("GBuffer1"), 1); shader->SendInteger(shader->GetUniformLocation("GBuffer2"), 2); shader->SendInteger(shader->GetUniformLocation("DepthBuffer"), 3); shader = RegisterDeferredShader("DeferredPointSpotLight", r_fragmentSource_PointSpotLight, sizeof(r_fragmentSource_PointSpotLight), basicVertexStage, &error); if (!shader) { NazaraError("Failed to register critical shader: " + error); return false; } shader->SendInteger(shader->GetUniformLocation("GBuffer0"), 0); shader->SendInteger(shader->GetUniformLocation("GBuffer1"), 1); shader->SendInteger(shader->GetUniformLocation("GBuffer2"), 2); shader->SendInteger(shader->GetUniformLocation("DepthBuffer"), 3); // Shaders optionnels (S'ils ne sont pas présents, le rendu minimal sera quand même assuré) shader = RegisterDeferredShader("DeferredBloomBright", r_fragmentSource_BloomBright, sizeof(r_fragmentSource_BloomBright), ppVertexStage, &error); if (shader) shader->SendInteger(shader->GetUniformLocation("ColorTexture"), 0); else { NazaraWarning("Failed to register bloom (bright pass) shader, certain features will not work: " + error); } shader = RegisterDeferredShader("DeferredBloomFinal", r_fragmentSource_BloomFinal, sizeof(r_fragmentSource_BloomFinal), ppVertexStage, &error); if (shader) { shader->SendInteger(shader->GetUniformLocation("ColorTexture"), 0); shader->SendInteger(shader->GetUniformLocation("BloomTexture"), 1); } else { NazaraWarning("Failed to register bloom (final pass) shader, certain features will not work: " + error); } shader = RegisterDeferredShader("DeferredFXAA", r_fragmentSource_FXAA, sizeof(r_fragmentSource_FXAA), ppVertexStage, &error); if (shader) shader->SendInteger(shader->GetUniformLocation("ColorTexture"), 0); else { NazaraWarning("Failed to register FXAA shader, certain features will not work: " + error); } shader = RegisterDeferredShader("DeferredGaussianBlur", r_fragmentSource_GaussianBlur, sizeof(r_fragmentSource_GaussianBlur), ppVertexStage, &error); if (shader) shader->SendInteger(shader->GetUniformLocation("ColorTexture"), 0); else { NazaraWarning("Failed to register gaussian blur shader, certain features will not work: " + error); } return true; }
int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to Create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); //register mouse callback function glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPosCallback(window, mouse_callback); //scroll callback function glfwSetScrollCallback(window, scroll_callback); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; return -1; } glViewport(0, 0, WIDTH, HEIGHT); Shader shader = Shader("shaders\\vertexShader.vshader", "shaders\\fragment.fshader"); //deal with vertices GLfloat vertices1[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; /* //vertices //texture coords 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f 0.55f, 0.55f, 0.55f, 0.45f, 0.45f, 0.45f, 0.45f, 0.55f */ GLuint indices[] = { 0,1,3, 1,2,3 }; /* */ GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices1), vertices1, GL_STATIC_DRAW); /* */ GLuint EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //**** MUST NOT have this line!!! **** glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); /* glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); */ glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); //unbind VBO VAO glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); //Load Texture GLint width, height; unsigned char* image = SOIL_load_image("src/container.jpg", &width, &height, 0, SOIL_LOAD_RGB); GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // Set texture wrapping to GL_REPEAT glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Set texture filtering 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_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); GLuint texture_2; glGenTextures(1, &texture_2); glBindTexture(GL_TEXTURE_2D, texture_2); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); image = SOIL_load_image("src/awesomeface.png", &width, &height, 0, SOIL_LOAD_RGB); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); glEnable(GL_DEPTH_TEST); //cube location arrays glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; while (!glfwWindowShouldClose(window)) { GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastTime; lastTime = currentFrame; glfwPollEvents(); doMovement(); //rendering command glClearColor(0.1f, 0.1f, 0.2f, 1.0f); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); shader.Use(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); GLuint textLocation = glGetUniformLocation(shader.ProgramID, "ourTexture"); glUniform1i(textLocation, 0); /* */ glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture_2); textLocation = glGetUniformLocation(shader.ProgramID, "ourTexture2"); glUniform1i(textLocation, 1); glUniform1f(glGetUniformLocation(shader.ProgramID, "mixrate"), g_mixrate); /* */ glBindVertexArray(VAO); for (int i = 0; i < 10; ++i) { glm::mat4 model, view, projection; model = glm::translate(model, cubePositions[i]); GLfloat angle = 20.0f * i; if (i % 3 == 0){ angle *= glfwGetTime(); } model = glm::rotate(model, glm::radians(angle), glm::vec3(0.5f, 1.0f, 0.0f)); view = camera.GetViewMatrix(); projection = glm::perspective(camera.Zoom, (float)WIDTH / (float)HEIGHT, 0.1f, 100.0f); glUniformMatrix4fv(glGetUniformLocation(shader.ProgramID, "model"), 1, GL_FALSE, glm::value_ptr(model)); glUniformMatrix4fv(glGetUniformLocation(shader.ProgramID, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(shader.ProgramID, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); //glDrawArrays(GL_TRIANGLES, 0, 3); //swap buffer avoid flert-prob glfwSwapBuffers(window); } glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glfwTerminate(); return 0; }
/// Initialize all resources provided by this manager. /// /// @see Shutdown(), PostConfigUpdate() void RenderResourceManager::Initialize() { // Release any existing resources. Shutdown(); // Get the renderer and graphics configuration. Renderer* pRenderer = Renderer::GetStaticInstance(); if( !pRenderer ) { return; } Config& rConfig = Config::GetStaticInstance(); StrongPtr< GraphicsConfig > spGraphicsConfig( rConfig.GetConfigObject< GraphicsConfig >( Name( TXT( "GraphicsConfig" ) ) ) ); if( !spGraphicsConfig ) { HELIUM_TRACE( TRACE_ERROR, TXT( "RenderResourceManager::Initialize(): Initialization failed; missing GraphicsConfig.\n" ) ); return; } // Create the standard rasterizer states. RRasterizerState::Description rasterizerStateDesc; rasterizerStateDesc.fillMode = RENDERER_FILL_MODE_SOLID; rasterizerStateDesc.cullMode = RENDERER_CULL_MODE_BACK; rasterizerStateDesc.winding = RENDERER_WINDING_CLOCKWISE; rasterizerStateDesc.depthBias = 0; rasterizerStateDesc.slopeScaledDepthBias = 0.0f; m_rasterizerStates[ RASTERIZER_STATE_DEFAULT ] = pRenderer->CreateRasterizerState( rasterizerStateDesc ); HELIUM_ASSERT( m_rasterizerStates[ RASTERIZER_STATE_DEFAULT ] ); rasterizerStateDesc.cullMode = RENDERER_CULL_MODE_NONE; m_rasterizerStates[ RASTERIZER_STATE_DOUBLE_SIDED ] = pRenderer->CreateRasterizerState( rasterizerStateDesc ); HELIUM_ASSERT( m_rasterizerStates[ RASTERIZER_STATE_DOUBLE_SIDED ] ); rasterizerStateDesc.depthBias = 1; rasterizerStateDesc.slopeScaledDepthBias = 2.0f; m_rasterizerStates[ RASTERIZER_STATE_SHADOW_DEPTH ] = pRenderer->CreateRasterizerState( rasterizerStateDesc ); HELIUM_ASSERT( m_rasterizerStates[ RASTERIZER_STATE_SHADOW_DEPTH ] ); rasterizerStateDesc.depthBias = 0; rasterizerStateDesc.slopeScaledDepthBias = 0.0f; rasterizerStateDesc.fillMode = RENDERER_FILL_MODE_WIREFRAME; m_rasterizerStates[ RASTERIZER_STATE_WIREFRAME_DOUBLE_SIDED ] = pRenderer->CreateRasterizerState( rasterizerStateDesc ); HELIUM_ASSERT( m_rasterizerStates[ RASTERIZER_STATE_WIREFRAME_DOUBLE_SIDED ] ); rasterizerStateDesc.cullMode = RENDERER_CULL_MODE_BACK; m_rasterizerStates[ RASTERIZER_STATE_WIREFRAME ] = pRenderer->CreateRasterizerState( rasterizerStateDesc ); HELIUM_ASSERT( m_rasterizerStates[ RASTERIZER_STATE_WIREFRAME ] ); // Create the standard blend states. RBlendState::Description blendStateDesc; blendStateDesc.bBlendEnable = false; m_blendStates[ BLEND_STATE_OPAQUE ] = pRenderer->CreateBlendState( blendStateDesc ); HELIUM_ASSERT( m_blendStates[ BLEND_STATE_OPAQUE ] ); blendStateDesc.colorWriteMask = 0; m_blendStates[ BLEND_STATE_NO_COLOR ] = pRenderer->CreateBlendState( blendStateDesc ); HELIUM_ASSERT( m_blendStates[ BLEND_STATE_NO_COLOR ] ); blendStateDesc.colorWriteMask = RENDERER_COLOR_WRITE_MASK_FLAG_ALL; blendStateDesc.bBlendEnable = true; blendStateDesc.sourceFactor = RENDERER_BLEND_FACTOR_SRC_ALPHA; blendStateDesc.destinationFactor = RENDERER_BLEND_FACTOR_INV_SRC_ALPHA; blendStateDesc.function = RENDERER_BLEND_FUNCTION_ADD; m_blendStates[ BLEND_STATE_TRANSPARENT ] = pRenderer->CreateBlendState( blendStateDesc ); HELIUM_ASSERT( m_blendStates[ BLEND_STATE_TRANSPARENT ] ); blendStateDesc.sourceFactor = RENDERER_BLEND_FACTOR_ONE; blendStateDesc.destinationFactor = RENDERER_BLEND_FACTOR_ONE; m_blendStates[ BLEND_STATE_ADDITIVE ] = pRenderer->CreateBlendState( blendStateDesc ); HELIUM_ASSERT( m_blendStates[ BLEND_STATE_ADDITIVE ] ); blendStateDesc.function = RENDERER_BLEND_FUNCTION_REVERSE_SUBTRACT; m_blendStates[ BLEND_STATE_SUBTRACTIVE ] = pRenderer->CreateBlendState( blendStateDesc ); HELIUM_ASSERT( m_blendStates[ BLEND_STATE_SUBTRACTIVE ] ); blendStateDesc.sourceFactor = RENDERER_BLEND_FACTOR_DEST_COLOR; blendStateDesc.destinationFactor = RENDERER_BLEND_FACTOR_ZERO; blendStateDesc.function = RENDERER_BLEND_FUNCTION_ADD; m_blendStates[ BLEND_STATE_MODULATE ] = pRenderer->CreateBlendState( blendStateDesc ); HELIUM_ASSERT( m_blendStates[ BLEND_STATE_MODULATE ] ); // Create the standard depth/stencil states. RDepthStencilState::Description depthStateDesc; depthStateDesc.stencilWriteMask = 0; depthStateDesc.bStencilTestEnable = false; depthStateDesc.depthFunction = RENDERER_COMPARE_FUNCTION_LESS_EQUAL; depthStateDesc.bDepthTestEnable = true; depthStateDesc.bDepthWriteEnable = true; m_depthStencilStates[ DEPTH_STENCIL_STATE_DEFAULT ] = pRenderer->CreateDepthStencilState( depthStateDesc ); HELIUM_ASSERT( m_depthStencilStates[ DEPTH_STENCIL_STATE_DEFAULT ] ); depthStateDesc.bDepthWriteEnable = false; m_depthStencilStates[ DEPTH_STENCIL_STATE_TEST_ONLY ] = pRenderer->CreateDepthStencilState( depthStateDesc ); HELIUM_ASSERT( m_depthStencilStates[ DEPTH_STENCIL_STATE_TEST_ONLY ] ); depthStateDesc.bDepthTestEnable = false; m_depthStencilStates[ DEPTH_STENCIL_STATE_NONE ] = pRenderer->CreateDepthStencilState( depthStateDesc ); HELIUM_ASSERT( m_depthStencilStates[ DEPTH_STENCIL_STATE_NONE ] ); // Create the standard sampler states that are not dependent on configuration settings. RSamplerState::Description samplerStateDesc; samplerStateDesc.filter = RENDERER_TEXTURE_FILTER_MIN_POINT_MAG_POINT_MIP_POINT; samplerStateDesc.addressModeW = RENDERER_TEXTURE_ADDRESS_MODE_CLAMP; samplerStateDesc.mipLodBias = 0; samplerStateDesc.maxAnisotropy = spGraphicsConfig->GetMaxAnisotropy(); for( size_t addressModeIndex = 0; addressModeIndex < RENDERER_TEXTURE_ADDRESS_MODE_MAX; ++addressModeIndex ) { ERendererTextureAddressMode addressMode = static_cast< ERendererTextureAddressMode >( addressModeIndex ); samplerStateDesc.addressModeU = addressMode; samplerStateDesc.addressModeV = addressMode; samplerStateDesc.addressModeW = addressMode; m_samplerStates[ TEXTURE_FILTER_POINT ][ addressModeIndex ] = pRenderer->CreateSamplerState( samplerStateDesc ); HELIUM_ASSERT( m_samplerStates[ TEXTURE_FILTER_POINT ][ addressModeIndex ] ); } // Create the standard set of mesh vertex descriptions. RVertexDescription::Element vertexElements[ 6 ]; vertexElements[ 0 ].type = RENDERER_VERTEX_DATA_TYPE_FLOAT32_3; vertexElements[ 0 ].semantic = RENDERER_VERTEX_SEMANTIC_POSITION; vertexElements[ 0 ].semanticIndex = 0; vertexElements[ 0 ].bufferIndex = 0; vertexElements[ 1 ].type = RENDERER_VERTEX_DATA_TYPE_UINT8_4_NORM; vertexElements[ 1 ].semantic = RENDERER_VERTEX_SEMANTIC_COLOR; vertexElements[ 1 ].semanticIndex = 0; vertexElements[ 1 ].bufferIndex = 0; vertexElements[ 2 ].type = RENDERER_VERTEX_DATA_TYPE_FLOAT16_2; vertexElements[ 2 ].semantic = RENDERER_VERTEX_SEMANTIC_TEXCOORD; vertexElements[ 2 ].semanticIndex = 0; vertexElements[ 2 ].bufferIndex = 0; vertexElements[ 3 ].type = RENDERER_VERTEX_DATA_TYPE_FLOAT32_2; vertexElements[ 3 ].semantic = RENDERER_VERTEX_SEMANTIC_TEXCOORD; vertexElements[ 3 ].semanticIndex = 1; vertexElements[ 3 ].bufferIndex = 0; m_spSimpleVertexDescription = pRenderer->CreateVertexDescription( vertexElements, 2 ); HELIUM_ASSERT( m_spSimpleVertexDescription ); m_spSimpleTexturedVertexDescription = pRenderer->CreateVertexDescription( vertexElements, 3 ); HELIUM_ASSERT( m_spSimpleTexturedVertexDescription ); m_spProjectedVertexDescription = pRenderer->CreateVertexDescription( vertexElements, 4 ); HELIUM_ASSERT( m_spProjectedVertexDescription ); vertexElements[ 1 ].type = RENDERER_VERTEX_DATA_TYPE_UINT8_4_NORM; vertexElements[ 1 ].semantic = RENDERER_VERTEX_SEMANTIC_NORMAL; vertexElements[ 1 ].semanticIndex = 0; vertexElements[ 1 ].bufferIndex = 0; vertexElements[ 2 ].type = RENDERER_VERTEX_DATA_TYPE_UINT8_4_NORM; vertexElements[ 2 ].semantic = RENDERER_VERTEX_SEMANTIC_TANGENT; vertexElements[ 2 ].semanticIndex = 0; vertexElements[ 2 ].bufferIndex = 0; vertexElements[ 3 ].type = RENDERER_VERTEX_DATA_TYPE_UINT8_4_NORM; vertexElements[ 3 ].semantic = RENDERER_VERTEX_SEMANTIC_COLOR; vertexElements[ 3 ].semanticIndex = 0; vertexElements[ 3 ].bufferIndex = 0; vertexElements[ 4 ].type = RENDERER_VERTEX_DATA_TYPE_FLOAT16_2; vertexElements[ 4 ].semantic = RENDERER_VERTEX_SEMANTIC_TEXCOORD; vertexElements[ 4 ].semanticIndex = 0; vertexElements[ 4 ].bufferIndex = 0; vertexElements[ 5 ].type = RENDERER_VERTEX_DATA_TYPE_FLOAT16_2; vertexElements[ 5 ].semantic = RENDERER_VERTEX_SEMANTIC_TEXCOORD; vertexElements[ 5 ].semanticIndex = 1; vertexElements[ 5 ].bufferIndex = 0; m_staticMeshVertexDescriptions[ 0 ] = pRenderer->CreateVertexDescription( vertexElements, 5 ); HELIUM_ASSERT( m_staticMeshVertexDescriptions[ 0 ] ); m_staticMeshVertexDescriptions[ 1 ] = pRenderer->CreateVertexDescription( vertexElements, 6 ); HELIUM_ASSERT( m_staticMeshVertexDescriptions[ 1 ] ); vertexElements[ 1 ].type = RENDERER_VERTEX_DATA_TYPE_UINT8_4_NORM; vertexElements[ 1 ].semantic = RENDERER_VERTEX_SEMANTIC_BLENDWEIGHT; vertexElements[ 1 ].semanticIndex = 0; vertexElements[ 1 ].bufferIndex = 0; vertexElements[ 2 ].type = RENDERER_VERTEX_DATA_TYPE_UINT8_4; vertexElements[ 2 ].semantic = RENDERER_VERTEX_SEMANTIC_BLENDINDICES; vertexElements[ 2 ].semanticIndex = 0; vertexElements[ 2 ].bufferIndex = 0; vertexElements[ 3 ].type = RENDERER_VERTEX_DATA_TYPE_UINT8_4_NORM; vertexElements[ 3 ].semantic = RENDERER_VERTEX_SEMANTIC_NORMAL; vertexElements[ 3 ].semanticIndex = 0; vertexElements[ 3 ].bufferIndex = 0; vertexElements[ 4 ].type = RENDERER_VERTEX_DATA_TYPE_UINT8_4_NORM; vertexElements[ 4 ].semantic = RENDERER_VERTEX_SEMANTIC_TANGENT; vertexElements[ 4 ].semanticIndex = 0; vertexElements[ 4 ].bufferIndex = 0; vertexElements[ 5 ].type = RENDERER_VERTEX_DATA_TYPE_FLOAT16_2; vertexElements[ 5 ].semantic = RENDERER_VERTEX_SEMANTIC_TEXCOORD; vertexElements[ 5 ].semanticIndex = 0; vertexElements[ 5 ].bufferIndex = 0; m_spSkinnedMeshVertexDescription = pRenderer->CreateVertexDescription( vertexElements, 6 ); HELIUM_ASSERT( m_spSkinnedMeshVertexDescription ); vertexElements[ 0 ].type = RENDERER_VERTEX_DATA_TYPE_FLOAT32_2; vertexElements[ 0 ].semantic = RENDERER_VERTEX_SEMANTIC_POSITION; vertexElements[ 0 ].semanticIndex = 0; vertexElements[ 0 ].bufferIndex = 0; vertexElements[ 1 ].type = RENDERER_VERTEX_DATA_TYPE_UINT8_4_NORM; vertexElements[ 1 ].semantic = RENDERER_VERTEX_SEMANTIC_COLOR; vertexElements[ 1 ].semanticIndex = 0; vertexElements[ 1 ].bufferIndex = 0; vertexElements[ 2 ].type = RENDERER_VERTEX_DATA_TYPE_FLOAT16_2; vertexElements[ 2 ].semantic = RENDERER_VERTEX_SEMANTIC_TEXCOORD; vertexElements[ 2 ].semanticIndex = 0; vertexElements[ 2 ].bufferIndex = 0; m_spScreenVertexDescription = pRenderer->CreateVertexDescription( vertexElements, 3 ); HELIUM_ASSERT( m_spScreenVertexDescription ); // Create configuration-dependent render resources. PostConfigUpdate(); // Attempt to load the depth-only pre-pass shader. #pragma TODO( "XXX TMC: Migrate to a more data-driven solution." ) GameObjectLoader* pObjectLoader = GameObjectLoader::GetStaticInstance(); HELIUM_ASSERT( pObjectLoader ); GameObjectPath prePassShaderPath; HELIUM_VERIFY( prePassShaderPath.Set( HELIUM_PACKAGE_PATH_CHAR_STRING TXT( "Shaders" ) HELIUM_OBJECT_PATH_CHAR_STRING TXT( "PrePass.hlsl" ) ) ); GameObjectPtr spPrePassShader; HELIUM_VERIFY( pObjectLoader->LoadObject( prePassShaderPath, spPrePassShader ) ); Shader* pPrePassShader = Reflect::SafeCast< Shader >( spPrePassShader.Get() ); HELIUM_ASSERT( pPrePassShader ); if( pPrePassShader ) { size_t loadId = pPrePassShader->BeginLoadVariant( RShader::TYPE_VERTEX, 0 ); HELIUM_ASSERT( IsValid( loadId ) ); if( IsValid( loadId ) ) { while( !pPrePassShader->TryFinishLoadVariant( loadId, m_spPrePassVertexShader ) ) { pObjectLoader->Tick(); } } } // Attempt to load the simple world-space, simple screen-space, and screen-space text shaders. #pragma TODO( "XXX TMC: Migrate to a more data-driven solution." ) GameObjectPath shaderPath; GameObjectPtr spShader; Shader* pShader; HELIUM_VERIFY( shaderPath.Set( HELIUM_PACKAGE_PATH_CHAR_STRING TXT( "Shaders" ) HELIUM_OBJECT_PATH_CHAR_STRING TXT( "Simple.hlsl" ) ) ); HELIUM_VERIFY( pObjectLoader->LoadObject( shaderPath, spShader ) ); pShader = Reflect::SafeCast< Shader >( spShader.Get() ); HELIUM_ASSERT( pShader ); if( pShader ) { size_t loadId = pShader->BeginLoadVariant( RShader::TYPE_VERTEX, 0 ); HELIUM_ASSERT( IsValid( loadId ) ); if( IsValid( loadId ) ) { while( !pShader->TryFinishLoadVariant( loadId, m_spSimpleWorldSpaceVertexShader ) ) { pObjectLoader->Tick(); } } loadId = pShader->BeginLoadVariant( RShader::TYPE_PIXEL, 0 ); HELIUM_ASSERT( IsValid( loadId ) ); if( IsValid( loadId ) ) { while( !pShader->TryFinishLoadVariant( loadId, m_spSimpleWorldSpacePixelShader ) ) { pObjectLoader->Tick(); } } } HELIUM_VERIFY( shaderPath.Set( HELIUM_PACKAGE_PATH_CHAR_STRING TXT( "Shaders" ) HELIUM_OBJECT_PATH_CHAR_STRING TXT( "ScreenSpaceTexture.hlsl" ) ) ); HELIUM_VERIFY( pObjectLoader->LoadObject( shaderPath, spShader ) ); pShader = Reflect::SafeCast< Shader >( spShader.Get() ); HELIUM_ASSERT( pShader ); if( pShader ) { size_t loadId = pShader->BeginLoadVariant( RShader::TYPE_VERTEX, 0 ); HELIUM_ASSERT( IsValid( loadId ) ); if( IsValid( loadId ) ) { while( !pShader->TryFinishLoadVariant( loadId, m_spSimpleScreenSpaceVertexShader ) ) { pObjectLoader->Tick(); } } loadId = pShader->BeginLoadVariant( RShader::TYPE_PIXEL, 0 ); HELIUM_ASSERT( IsValid( loadId ) ); if( IsValid( loadId ) ) { while( !pShader->TryFinishLoadVariant( loadId, m_spSimpleScreenSpacePixelShader ) ) { pObjectLoader->Tick(); } } } HELIUM_VERIFY( shaderPath.Set( HELIUM_PACKAGE_PATH_CHAR_STRING TXT( "Shaders" ) HELIUM_OBJECT_PATH_CHAR_STRING TXT( "ScreenText.hlsl" ) ) ); HELIUM_VERIFY( pObjectLoader->LoadObject( shaderPath, spShader ) ); pShader = Reflect::SafeCast< Shader >( spShader.Get() ); HELIUM_ASSERT( pShader ); if( pShader ) { size_t loadId = pShader->BeginLoadVariant( RShader::TYPE_VERTEX, 0 ); HELIUM_ASSERT( IsValid( loadId ) ); if( IsValid( loadId ) ) { while( !pShader->TryFinishLoadVariant( loadId, m_spScreenTextVertexShader ) ) { pObjectLoader->Tick(); } } loadId = pShader->BeginLoadVariant( RShader::TYPE_PIXEL, 0 ); HELIUM_ASSERT( IsValid( loadId ) ); if( IsValid( loadId ) ) { while( !pShader->TryFinishLoadVariant( loadId, m_spScreenTextPixelShader ) ) { pObjectLoader->Tick(); } } } // Attempt to load the debug fonts. #pragma TODO( "XXX TMC: Migrate to a more data-driven solution." ) GameObjectPath fontPath; GameObjectPtr spFont; HELIUM_VERIFY( fontPath.Set( HELIUM_PACKAGE_PATH_CHAR_STRING TXT( "Fonts" ) HELIUM_OBJECT_PATH_CHAR_STRING TXT( "DebugSmall" ) ) ); HELIUM_VERIFY( pObjectLoader->LoadObject( fontPath, spFont ) ); m_debugFonts[ DEBUG_FONT_SIZE_SMALL ] = Reflect::SafeCast< Font >( spFont.Get() ); spFont.Release(); HELIUM_VERIFY( fontPath.Set( HELIUM_PACKAGE_PATH_CHAR_STRING TXT( "Fonts" ) HELIUM_OBJECT_PATH_CHAR_STRING TXT( "DebugMedium" ) ) ); HELIUM_VERIFY( pObjectLoader->LoadObject( fontPath, spFont ) ); m_debugFonts[ DEBUG_FONT_SIZE_MEDIUM ] = Reflect::SafeCast< Font >( spFont.Get() ); spFont.Release(); HELIUM_VERIFY( fontPath.Set( HELIUM_PACKAGE_PATH_CHAR_STRING TXT( "Fonts" ) HELIUM_OBJECT_PATH_CHAR_STRING TXT( "DebugLarge" ) ) ); HELIUM_VERIFY( pObjectLoader->LoadObject( fontPath, spFont ) ); m_debugFonts[ DEBUG_FONT_SIZE_LARGE ] = Reflect::SafeCast< Font >( spFont.Get() ); spFont.Release(); }
static int engine_init_display(struct engine* engine) { // initialize OpenGL ES and EGL const EGLint attribs[] = { EGL_NATIVE_VISUAL_ID, WINDOW_FORMAT_RGB_565, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_BLUE_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_RED_SIZE, 5, EGL_DEPTH_SIZE,1, EGL_NONE }; EGLint w, h, dummy, format; EGLint numConfigs; EGLConfig config; EGLSurface surface; EGLContext context; EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); EGLint majorVersion; EGLint minorVersion; eglInitialize(display, &majorVersion, &minorVersion); //eglInitialize(display, 0, 0); LOGI("OpenGL %i.%i", majorVersion,minorVersion); //query num of configs int* num_conf = new int[1]; eglGetConfigs(display, NULL, 0, num_conf); //if configuration array is null it still returns the number of configurations int configurations = num_conf[0]; LOGI("total num configs: %i", configurations); //just some debugging info if the need arises... LOGI("EGL_OPENGL_ES2_BIT id:%i", EGL_OPENGL_ES2_BIT); //print the numerical code for the ES2 bit mask, etc LOGI("EGL_SURFACE_TYPE::EGL_WINDOW_BIT id:%i", EGL_WINDOW_BIT); LOGI("WINDOW_FORMAT_RGB_565 id:%i", WINDOW_FORMAT_RGB_565); //now query the configs EGLConfig* conf = new EGLConfig[configurations]; eglGetConfigs(display, conf, configurations, num_conf); int* depth = new int[1]; int* r = new int[1]; int* g = new int[1]; int* b = new int[1]; int* a = new int[1]; int* s = new int[1]; int* renderType = new int[1]; int* surfaceType = new int[1]; int* formatType = new int[1]; EGLConfig configToUse; //this is the one true config that we will use for(int i = 0; i < configurations; i++) { eglGetConfigAttrib(display, conf[i], EGL_DEPTH_SIZE, depth); eglGetConfigAttrib(display, conf[i], EGL_RED_SIZE, r); eglGetConfigAttrib(display, conf[i], EGL_GREEN_SIZE, g); eglGetConfigAttrib(display, conf[i], EGL_BLUE_SIZE, b); eglGetConfigAttrib(display, conf[i], EGL_ALPHA_SIZE, a); eglGetConfigAttrib(display, conf[i], EGL_RENDERABLE_TYPE, renderType); eglGetConfigAttrib(display, conf[i], EGL_STENCIL_SIZE, s); eglGetConfigAttrib(display, conf[i], EGL_SURFACE_TYPE, surfaceType); eglGetConfigAttrib(display, conf[i], EGL_NATIVE_VISUAL_ID, formatType); LOGI("(R%i,G%i,B%i,A%i)depth:(%i) stencil:(%i) surfaceType:(%i) renderType:(%i) formatType:(%i)",r[0],g[0],b[0],a[0],depth[0],s[0],surfaceType[0], renderType[0],formatType[0]); if((renderType[0] & EGL_OPENGL_ES2_BIT) > 0 && (surfaceType[0] & EGL_WINDOW_BIT) > 0 && (formatType[0] & WINDOW_FORMAT_RGB_565) > 0 && depth[0]>0) { configToUse=conf[i]; LOGI("Config #%i" , i ); LOGI("(R%i,G%i,B%i,A%i) %idepth %istencil %isurfaceType %iNativeVisualId",r[0],g[0],b[0],a[0],depth[0],s[0],surfaceType[0],formatType[0]); } } //bridge the pixel format back into android eglGetConfigAttrib(display, configToUse, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format); surface = eglCreateWindowSurface(display, configToUse, engine->app->window, NULL); if(surface == EGL_NO_SURFACE ) { LOGW("Error making surface, EGL_NO_SURFACE"); } //now create the OpenGL ES2 context const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION , 2, EGL_NONE }; context = eglCreateContext(display, configToUse, NULL, contextAttribs); if(context == EGL_NO_CONTEXT ) { LOGW("Error making context, EGL_NO_CONTEXT"); } if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { LOGW("Unable to eglMakeCurrent"); return -1; } eglQuerySurface(display, surface, EGL_WIDTH, &w); eglQuerySurface(display, surface, EGL_HEIGHT, &h); ContextWidth = w; ContextHeight = h; engine->display = display; engine->context = context; engine->surface = surface; engine->width = w; engine->height = h; engine->state.angle = 0; glEnable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); //GLubyte* rendererString = new GLubyte[512]; const GLubyte* rendererString = rendererString=glGetString(GL_VERSION); LOGI("Renderer: %s",rendererString); // // // LOAD ALL RESOURCES // // ////////////////// // PHONG SHADER // ////////////////// if(!PhongShader.createShader((char*)"phong.vs",(char*)"phong.fs")) { LOGE("Could not create phong program."); return false; } PositionAttributes = glGetAttribLocation(PhongShader.ID, "aPosition"); NormalAttributes = glGetAttribLocation(PhongShader.ID, "aNormal"); TexCoordAttributes = glGetAttribLocation(PhongShader.ID, "aTexCoords"); MVPMatrixUniform = glGetUniformLocation( PhongShader.ID, "MVPMatrixUniform" ); EyePosUniform = glGetUniformLocation(PhongShader.ID,"EyePosUniform"); LightPosUniform = glGetUniformLocation(PhongShader.ID,"LightPosUniform"); TextureSampler = glGetUniformLocation(PhongShader.ID,"sTexture"); LOGI("===PHONG-DEBUG VALUES==="); LOGI("PositionAttributes: %i",PositionAttributes); LOGI("NormalAttributes: %i",NormalAttributes); LOGI("TexCoordAttributes: %i",TexCoordAttributes); LOGI("MVPMatrixUniform: %i",MVPMatrixUniform); LOGI("EyePosUniform: %i",EyePosUniform); LOGI("LightPosUniform: %i",LightPosUniform); LOGI("TextureSampler: %i",TextureSampler); LOGI("===END==="); ////////////////// // DEPTH SHADER // ////////////////// if(!DepthShader.createShader((char*)"depthcolor.vs",(char*)"depthcolor.fs")) { LOGE("Could not create depth shader program."); return false; } DepthShaderMVPMatrixUniform = glGetUniformLocation(DepthShader.ID, "MVPMatrixUniform"); DepthShaderPositionAttributes = glGetAttribLocation(DepthShader.ID, "aPosition"); LOGI("===DEPTH-DEBUG VALUES==="); LOGI("DepthShaderPositionAttributes: %i",DepthShaderPositionAttributes); LOGI("DepthShaderMVPMatrixUniform: %i",DepthShaderMVPMatrixUniform); LOGI("===END==="); ///////////////////////////////// // TEXPASSTHRU (SKYBOX) SHADER // ///////////////////////////////// if(!TexPassThruShader.createShader((char*)"texpassthru.vs",(char*)"texpassthru.fs")) { LOGE("Could not create texpassthru program."); return false; } TexPassThruSampler = glGetUniformLocation(TexPassThruShader.ID,"sTexture"); TexPassThruMVPMatrixUniform = glGetUniformLocation(TexPassThruShader.ID,"MVPMatrixUniform"); TexPassThruPositionAttributes = glGetAttribLocation(TexPassThruShader.ID, "aPosition"); TexPassThruTexCoordAttributes = glGetAttribLocation(TexPassThruShader.ID, "aTexCoords"); LOGI("===TEXPASSTHRU-DEBUG VALUES==="); LOGI("TexPassThruSampler: %i",TexPassThruSampler); LOGI("TexPassThruMVPMatrixUniform: %i",TexPassThruMVPMatrixUniform); LOGI("TexPassThruPositionAttributes: %i",TexPassThruPositionAttributes); LOGI("TexPassThruTexCoordAttributes: %i",TexPassThruTexCoordAttributes); LOGI("===END==="); //////////////////////// // ENVIRONMENT SHADER // //////////////////////// if (!EnvironmentMappingShader.createShader((char*)"environmentcubemap.vs",(char*)"environmentcubemap.fs")) { LOGE("Could not create program."); return false; } EnvironmentMappingShaderMVPMatrixUniform=glGetUniformLocation(EnvironmentMappingShader.ID,"MVPMatrixUniform"); EnvironmentMappingShaderPositionAttributes=glGetAttribLocation(EnvironmentMappingShader.ID, "aPosition"); EnvironmentMappingShaderNormalAttributes=glGetAttribLocation(EnvironmentMappingShader.ID, "aNormal"); EnvironmentMappingShaderCubeSampler=glGetUniformLocation(EnvironmentMappingShader.ID,"sCubeTexture"); LOGI("===ENVIRONMENT-DEBUG VALUES==="); LOGI("EnvironmentMappingShaderCubeSampler: %i",EnvironmentMappingShaderCubeSampler); LOGI("EnvironmentMappingShaderMVPMatrixUniform: %i",EnvironmentMappingShaderMVPMatrixUniform); LOGI("EnvironmentMappingShaderPositionAttributes: %i",EnvironmentMappingShaderPositionAttributes); LOGI("TexPassThruTeEnvironmentMappingShaderNormalAttributesxCoordAttributes: %i",EnvironmentMappingShaderNormalAttributes); LOGI("===END==="); //Matrices esMatrixLoadIdentity(&MVPMatrix); //viewport glViewport(0, 0, w, h); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); checkGlError("glViewport"); //load resources internally from the APK StatueMesh.loadMesh((char*)"athena.obj"); checkGlError("loadMesh"); if(!StoneTexture.loadTexture((char*)"rockish.tga")) { LOGE("texture loading FAILED"); } CubeSkyBox.loadSkyBox(); if(!EnvironmentCubeTexture.loadCubeTexture()) LOGE("Could not load cube texture."); return 0; }
int main(int argc, char *argv[]) #endif { LOG_DEBUG("Opening window ..."); Window window = Window("Snowflake Sandbox", VideoMode(1280, 768)); Color clearColor = Color(50, 80, 80, 255); GLfloat vertexBufferData[] = { // Front face -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, // Back face -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, // Top face -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, // Bottom face -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, // Right face 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, // Left face -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0 }; GLfloat colorBufferData[] = { 0.583f, 0.771f, 0.014f, 0.609f, 0.115f, 0.436f, 0.327f, 0.483f, 0.844f, 0.822f, 0.569f, 0.201f, 0.435f, 0.602f, 0.223f, 0.310f, 0.747f, 0.185f, 0.597f, 0.770f, 0.761f, 0.559f, 0.436f, 0.730f, 0.359f, 0.583f, 0.152f, 0.483f, 0.596f, 0.789f, 0.559f, 0.861f, 0.639f, 0.195f, 0.548f, 0.859f, 0.014f, 0.184f, 0.576f, 0.771f, 0.328f, 0.970f, 0.406f, 0.615f, 0.116f, 0.676f, 0.977f, 0.133f, 0.971f, 0.572f, 0.833f, 0.140f, 0.616f, 0.489f, 0.997f, 0.513f, 0.064f, 0.945f, 0.719f, 0.592f, 0.543f, 0.021f, 0.978f, 0.279f, 0.317f, 0.505f, 0.167f, 0.620f, 0.077f, 0.347f, 0.857f, 0.137f, 0.055f, 0.953f, 0.042f, 0.714f, 0.505f, 0.345f, 0.783f, 0.290f, 0.734f, 0.722f, 0.645f, 0.174f, 0.302f, 0.455f, 0.848f, 0.225f, 0.587f, 0.040f, 0.517f, 0.713f, 0.338f, 0.053f, 0.959f, 0.120f, 0.393f, 0.621f, 0.362f, 0.673f, 0.211f, 0.457f, 0.820f, 0.883f, 0.371f, 0.982f, 0.099f, 0.879f }; GLushort indicesData[] = { 0, 1, 2, 0, 2, 3, // front 4, 5, 6, 4, 6, 7, // back 8, 9, 10, 8, 10, 11, // top 12, 13, 14, 12, 14, 15, // bottom 16, 17, 18, 16, 18, 19, // right 20, 21, 22, 20, 22, 23 // left }; VertexArray cube, cube2; IndexBuffer ibo(indicesData, std::end(indicesData) - std::begin(indicesData)); cube.AddBuffer(sfnew Buffer(vertexBufferData, sizeof(vertexBufferData), 3), 0); cube.AddBuffer(sfnew Buffer(colorBufferData, sizeof(colorBufferData), 3), 1); cube2.AddBuffer(sfnew Buffer(vertexBufferData, sizeof(vertexBufferData), 3), 0); cube2.AddBuffer(sfnew Buffer(colorBufferData, sizeof(colorBufferData), 3), 1); Matrix4 projection = Matrix4::Perspective(100.0f, window.GetSize().X / window.GetSize().Y, 0.1f, 100.f); Matrix4 view = Matrix4::LookAt(Vector3(4, 3, 3), Vector3(0, 0, 0), Vector3(0, 0.8f, 0)); Matrix4 model = Matrix4(1.0f); Matrix4 mvp = projection * view * model; Shader shader = Shader("tri_vertex.glsl", "tri_fragment.glsl"); shader.Enable(); while (!window.ShouldClose()) { window.Clear(clearColor); // Render here cube.Bind(); ibo.Bind(); model = Matrix4::Translation(Vector3(0, 0, 0)); mvp = projection * view * model; shader.SetUniformMat4("MVP", mvp); glDrawElements(GL_TRIANGLES, ibo.GetCount(), GL_UNSIGNED_SHORT, 0); ibo.Bind(); cube.Unbind(); cube2.Bind(); ibo.Bind(); model = Matrix4::Translation(Vector3(4, 0, 0)); mvp = projection * view * model; shader.SetUniformMat4("MVP", mvp); glDrawElements(GL_TRIANGLES, ibo.GetCount(), GL_UNSIGNED_SHORT, 0); ibo.Bind(); cube2.Unbind(); window.Display(); window.Update(); } window.Close(); #if _DEBUG LOG_DEBUG("PAUSING NOW!"); system("PAUSE"); #endif return EXIT_SUCCESS; }
void EditShaderDialog::writeToData(Shader& shader) { for(const auto& it : m_sourceWidgets) shader.setSource(it.first, it.second.sourceEdit->text().toStdString()); }
void Image::renderClassic (RendererClassic *renderer) { glEnable( GL_MULTISAMPLE ); glEnable( GL_SAMPLE_SHADING ); glMinSampleShading( 1.0f ); glDisable( GL_DEPTH_TEST ); glEnable( GL_STENCIL_TEST ); for (Uint32 o=0; o<objects.size(); ++o) { Object *obj = objects[o]; /////////////////////////////////////////////// //Render into stencil glStencilFunc( GL_ALWAYS, 0, 1 ); glStencilOp( GL_INVERT, GL_INVERT, GL_INVERT ); glColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE ); /////////////////////////////////////////////// //Render quads { Shader *shader = renderer->shaderQuads; shader->use(); Int32 uModelview = shader->program->getUniform( "modelview" ); glUniformMatrix4fv( uModelview, 1, false, (GLfloat*) matModelView.top().m ); Int32 uProjection = shader->program->getUniform( "projection" ); glUniformMatrix4fv( uProjection, 1, false, (GLfloat*) matProjection.top().m ); Int32 aPos = shader->program->getAttribute( "in_pos" ); glEnableVertexAttribArray( aPos ); glBindBuffer( GL_ARRAY_BUFFER, obj->bufQuads.getId() ); glVertexAttribPointer( aPos, 2, GL_FLOAT, false, sizeof( Vec2 ), 0 ); glDrawArrays( GL_TRIANGLES, 0, obj->quads.size() * 3 ); glDisableVertexAttribArray( aPos ); } /////////////////////////////////////////////// //Render contours { Shader *shader = renderer->shaderContour; shader->use(); Int32 uModelview = shader->program->getUniform( "modelview" ); glUniformMatrix4fv( uModelview, 1, false, (GLfloat*) matModelView.top().m ); Int32 uProjection = shader->program->getUniform( "projection" ); glUniformMatrix4fv( uProjection, 1, false, (GLfloat*) matProjection.top().m ); for (Uint32 c=0; c<obj->contours.size(); ++c) { Contour &cnt = obj->contours[c]; Int32 aPos = shader->program->getAttribute( "in_pos" ); glEnableVertexAttribArray( aPos ); glBindBuffer( GL_ARRAY_BUFFER, obj->bufContourPoints.getId() ); glVertexAttribPointer( aPos, 2, GL_FLOAT, false, sizeof( Vec2 ), 0 ); glDrawArrays( GL_TRIANGLE_FAN, cnt.start, cnt.length ); glDisableVertexAttribArray( aPos ); } } /////////////////////////////////////////////// //Render through stencil glStencilFunc( GL_EQUAL, 1, 1 ); glStencilOp( GL_ZERO, GL_ZERO, GL_ZERO ); glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE ); /////////////////////////////////////////////// //Render boundbox quad { Shader *shader = renderer->shader; shader->use(); Int32 uModelview = shader->program->getUniform( "modelview" ); glUniformMatrix4fv( uModelview, 1, false, (GLfloat*) matModelView.top().m ); Int32 uProjection = shader->program->getUniform( "projection" ); glUniformMatrix4fv( uProjection, 1, false, (GLfloat*) matProjection.top().m ); Int32 uColor = shader->program->getUniform( "color" ); glUniform4fv( uColor, 1, (GLfloat*) &obj->color ); Float coords[] = { obj->min.x, obj->min.y, obj->max.x, obj->min.y, obj->max.x, obj->max.y, obj->min.x, obj->max.y }; Int32 aPos = shader->program->getAttribute( "in_pos" ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glVertexAttribPointer( aPos, 2, GL_FLOAT, false, 2 * sizeof( Float ), coords ); glEnableVertexAttribArray( aPos ); glDrawArrays( GL_QUADS, 0, 4 ); glDisableVertexAttribArray( aPos ); } } glDisable( GL_STENCIL_TEST ); }
Material *MaterialManager::materialFromXMLNode(TiXmlNode *node) { TiXmlElement *nodeElement = node->ToElement(); if (!nodeElement) return NULL; // Skip comment nodes String mname = nodeElement->Attribute("name"); TiXmlNode* pChild, *pChild2,*pChild3; Shader *materialShader; ShaderBinding *newShaderBinding; vector<Shader*> materialShaders; vector<ShaderBinding*> newShaderBindings; vector<ShaderRenderTarget*> renderTargets; Material *newMaterial = new Material(mname); if(nodeElement->Attribute("blendingMode")) { newMaterial->blendingMode = atoi(nodeElement->Attribute("blendingMode")); } for (pChild3 = node->FirstChild(); pChild3 != 0; pChild3 = pChild3->NextSibling()) { TiXmlElement *pChild3Element = pChild3->ToElement(); if (!pChild3Element) continue; // Skip comment nodes if(strcmp(pChild3->Value(), "rendertargets") == 0) { if(pChild3Element->Attribute("type")) { if(strcmp(pChild3Element->Attribute("type"), "rgba_fp16") == 0) { newMaterial->fp16RenderTargets = true; } } for (pChild = pChild3->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { TiXmlElement *pChildElement = pChild->ToElement(); if (!pChildElement) continue; // Skip comment nodes if(strcmp(pChild->Value(), "rendertarget") == 0) { ShaderRenderTarget *newTarget = new ShaderRenderTarget; newTarget->id = pChildElement->Attribute("id"); newTarget->width = CoreServices::getInstance()->getRenderer()->getXRes(); newTarget->height = CoreServices::getInstance()->getRenderer()->getYRes(); newTarget->sizeMode = ShaderRenderTarget::SIZE_MODE_PIXELS; if(pChildElement->Attribute("width") && pChildElement->Attribute("height")) { newTarget->width = atof(pChildElement->Attribute("width")); newTarget->height = atof(pChildElement->Attribute("height")); if(pChildElement->Attribute("sizeMode")) { if(strcmp(pChildElement->Attribute("sizeMode"), "normalized") == 0) { if(newTarget->width > 1.0f) newTarget->width = 1.0f; if(newTarget->height > 1.0f) newTarget->height = 1.0f; newTarget->width = ((Number)CoreServices::getInstance()->getRenderer()->getXRes()) * newTarget->width; newTarget->height = ((Number)CoreServices::getInstance()->getRenderer()->getYRes()) * newTarget->height; } } } // Texture *newTexture = CoreServices::getInstance()->getMaterialManager()->createNewTexture(newTarget->width, newTarget->height, true); Texture *newTexture, *temp; CoreServices::getInstance()->getRenderer()->createRenderTextures(&newTexture, &temp, (int)newTarget->width, (int)newTarget->height, newMaterial->fp16RenderTargets); newTexture->setResourceName(newTarget->id); //CoreServices::getInstance()->getResourceManager()->addResource(newTexture); newTarget->texture = newTexture; renderTargets.push_back(newTarget); } } } } for (pChild3 = node->FirstChild(); pChild3 != 0; pChild3 = pChild3->NextSibling()) { TiXmlElement *pChild3Element = pChild3->ToElement(); if (!pChild3Element) continue; // Skip comment nodes if(strcmp(pChild3->Value(), "shader") == 0) { materialShader = setShaderFromXMLNode(pChild3); if(materialShader) { newShaderBinding = materialShader->createBinding(); materialShaders.push_back(materialShader); newShaderBindings.push_back(newShaderBinding); for (pChild = pChild3->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { TiXmlElement *pChildElement = pChild->ToElement(); if (!pChildElement) continue; // Skip comment nodes if(strcmp(pChild->Value(), "params") == 0) { for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) { TiXmlElement *pChild2Element = pChild2->ToElement(); if (!pChild2Element) continue; // Skip comment nodes if(strcmp(pChild2->Value(), "param") == 0){ String pname = pChild2Element->Attribute("name"); String ptype = pChild2Element->Attribute("type"); String pvalue = pChild2Element->Attribute("value"); newShaderBinding->addParam(ptype, pname, pvalue); } } } if(strcmp(pChild->Value(), "targettextures") == 0) { for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) { TiXmlElement *pChild2Element = pChild2->ToElement(); if (!pChild2Element) continue; // Skip comment nodes if(strcmp(pChild2->Value(), "targettexture") == 0){ RenderTargetBinding* newBinding = new RenderTargetBinding; newBinding->id = pChild2Element->Attribute("id"); newBinding->name = ""; if(pChild2Element->Attribute("name")) { newBinding->name = pChild2Element->Attribute("name"); } String mode = pChild2Element->Attribute("mode"); if(strcmp(mode.c_str(), "in") == 0) { newBinding->mode = RenderTargetBinding::MODE_IN; } else { newBinding->mode = RenderTargetBinding::MODE_OUT; } newShaderBinding->addRenderTargetBinding(newBinding); //Texture *texture = (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, newBinding->id); // newBinding->texture = texture; for(int l=0; l < renderTargets.size(); l++) { if(renderTargets[l]->id == newBinding->id) { printf("Assigning texture to %s\n", newBinding->id.c_str()); newBinding->texture = renderTargets[l]->texture; newBinding->width = renderTargets[l]->width; newBinding->height = renderTargets[l]->height; } } if(newBinding->mode == RenderTargetBinding::MODE_IN) { newShaderBinding->addTexture(newBinding->name, newBinding->texture); } } } } if(strcmp(pChild->Value(), "textures") == 0) { for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) { TiXmlElement *pChild2Element = pChild2->ToElement(); if (!pChild2Element) continue; // Skip comment nodes if(strcmp(pChild2->Value(), "texture") == 0){ String tname = ""; if(pChild2Element->Attribute("name")) { tname = pChild2Element->Attribute("name"); } Texture *texture = CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(pChild2Element->GetText()); newShaderBinding->addTexture(tname,texture); // newShaderBinding->addTexture(tname, (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, pChild2Element->GetText())); } if(strcmp(pChild2->Value(), "cubemap") == 0){ String tname = ""; if(pChild2Element->Attribute("name")) { tname = pChild2Element->Attribute("name"); } newShaderBinding->addCubemap(tname, (Cubemap*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_CUBEMAP, pChild2Element->GetText())); } } } } } } } for(int i=0; i< materialShaders.size(); i++) { newMaterial->addShader(materialShaders[i],newShaderBindings[i]); } for(int i=0; i< renderTargets.size(); i++) { newMaterial->addShaderRenderTarget(renderTargets[i]); } return newMaterial; }
void GLAppMain::render_pbuf() { pbuffer->enable(); glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); positions->bind(); glActiveTexture(GL_TEXTURE1); speeds->bind(); glActiveTexture(GL_TEXTURE2); normals->bind(); glActiveTexture(GL_TEXTURE0); /* render to speeds array */ speeds_shader->bind(); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex3f(0,0,0); glTexCoord2f(0,1); glVertex3f(0,1,0); glTexCoord2f(1,1); glVertex3f(1,1,0); glTexCoord2f(1,0); glVertex3f(1,0,0); glEnd(); speeds_shader->unbind(); glActiveTexture(GL_TEXTURE1); speeds->copy(); glActiveTexture(GL_TEXTURE0); /* render to positions array */ positions_shader->bind(); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex3f(0,0,0); glTexCoord2f(0,1); glVertex3f(0,1,0); glTexCoord2f(1,1); glVertex3f(1,1,0); glTexCoord2f(1,0); glVertex3f(1,0,0); glEnd(); positions_shader->unbind(); positions->copy(); /* copy positions to buffer */ vertex_buffer->bind(GL_PIXEL_PACK_BUFFER_ARB); glReadPixels(0,0,SIZE,SIZE,GL_RGBA,GL_FLOAT,0); vertex_buffer->unbind(GL_PIXEL_PACK_BUFFER_ARB); /* render to normals array */ normals_shader->bind(); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex3f(0,0,0); glTexCoord2f(0,1); glVertex3f(0,1,0); glTexCoord2f(1,1); glVertex3f(1,1,0); glTexCoord2f(1,0); glVertex3f(1,0,0); glEnd(); normals_shader->unbind(); glActiveTexture(GL_TEXTURE2); normals->copy(); glActiveTexture(GL_TEXTURE0); /* copy normals to buffer */ normal_buffer->bind(GL_PIXEL_PACK_BUFFER_ARB); glReadPixels(0,0,SIZE,SIZE,GL_RGBA,GL_FLOAT,0); normal_buffer->unbind(GL_PIXEL_PACK_BUFFER_ARB); pbuffer->disable(); }