void drawScene2(){ glTranslatef(0,0,-16); glPushMatrix(); glTranslatef(0, 0, -ZOOM); glPushMatrix(); static float lightRotate = 0.0f; lightRotate += 0.3; glRotatef(lightRotate / 80.0 * 180.0, 0.11111, 0.3, 1.0); glLightfv(GL_LIGHT0, GL_POSITION, std_light_pos); glLightfv(GL_LIGHT1, GL_POSITION, std_light_pos); glLightfv(GL_LIGHT2, GL_POSITION, std_light_pos); glLightfv(GL_LIGHT0, GL_POSITION, light_position1); glLightfv(GL_LIGHT1, GL_POSITION, light_position2); glLightfv(GL_LIGHT2, GL_POSITION, light_position3); glPopMatrix(); glShadeModel(GL_FLAT); // TOP ROW glPushMatrix(); glTranslatef(-3, 3, 0); glRotatef(-mouseDragSumY * MOUSE_SENSITIVITY, 1, 0, 0); glRotatef(-mouseDragSumX * MOUSE_SENSITIVITY, 0, 1, 0); glRotatef(-90, 0, 0, 1); drawGeodesicPoints(&geodesicV3); glPopMatrix(); glPushMatrix(); glTranslatef(0, 3, 0); glRotatef(-mouseDragSumY * MOUSE_SENSITIVITY, 1, 0, 0); glRotatef(-mouseDragSumX * MOUSE_SENSITIVITY, 0, 1, 0); glRotatef(-90, 0, 0, 1); drawGeodesicLines(&geodesicV3); glPopMatrix(); glPushMatrix(); glTranslatef(3, 3, 0); glRotatef(-mouseDragSumY * MOUSE_SENSITIVITY, 1, 0, 0); glRotatef(-mouseDragSumX * MOUSE_SENSITIVITY, 0, 1, 0); glRotatef(-90, 0, 0, 1); drawGeodesicTriangles(&geodesicV3); glPopMatrix(); // MIDDLE ROW glPushMatrix(); glTranslatef(-3, 0, 0); glRotatef(-mouseDragSumY * MOUSE_SENSITIVITY, 1, 0, 0); glRotatef(-mouseDragSumX * MOUSE_SENSITIVITY, 0, 1, 0); drawGeodesicExtrudedTriangles(&m); glPopMatrix(); glPushMatrix(); glScalef(1.618, 1.618, 1.618); glRotatef(-mouseDragSumY * MOUSE_SENSITIVITY, 1, 0, 0); glRotatef(-mouseDragSumX * MOUSE_SENSITIVITY, 0, 1, 0); glRotatef(-90, 0, 0, 1); drawGeodesicLines(&geodesicV2); glDisable(GL_LIGHTING); glColor3f(1.0, 1.0, 1.0); drawGeodesicVertexNormalLines(&normalsV2); glColor3f(0.0, 1.0, 1.0); drawGeodesicLineNormalLines(&normalsV2); glColor3f(1.0, 0.0, 1.0); drawGeodesicFaceNormalLines(&normalsV2); glEnable(GL_LIGHTING); glPopMatrix(); glPushMatrix(); glTranslatef(3, 0, 0); glRotatef(-mouseDragSumY * MOUSE_SENSITIVITY, 1, 0, 0); glRotatef(-mouseDragSumX * MOUSE_SENSITIVITY, 0, 1, 0); glRotatef(-90, 0, 0, 1); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glVertexPointer(3, GL_FLOAT, 0, t.data); glNormalPointer(GL_FLOAT, 0, geo.pointNormals); glDrawElements(GL_TRIANGLES, geo.numFaces*3, GL_UNSIGNED_SHORT, geo.faces); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glPopMatrix(); // BOTTOM ROW glPushMatrix(); glTranslatef(-3, -3, 0); glRotatef(-mouseDragSumY * MOUSE_SENSITIVITY, 1, 0, 0); glRotatef(-mouseDragSumX * MOUSE_SENSITIVITY, 0, 1, 0); glPushMatrix(); glRotatef(-90, 0, 0, 1); drawGeodesicExtrudedTriangles(&m); glPopMatrix(); glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); glColor3f(0.5, 0.5, 0.5); drawGeodesicCropPlanes(&planes); glEnable(GL_CULL_FACE); glEnable(GL_LIGHTING); glPopMatrix(); glPushMatrix(); glTranslatef(0, -3, 0); glRotatef(-mouseDragSumY * MOUSE_SENSITIVITY, 1, 0, 0); glRotatef(-mouseDragSumX * MOUSE_SENSITIVITY, 0, 1, 0); glRotatef(-90, 0, 0, 1); drawDomeMeshTriangles(&domeV3, &domeMeshV3); glPopMatrix(); glPushMatrix(); glTranslatef(3, -3, 0); glRotatef(-mouseDragSumY * MOUSE_SENSITIVITY, 1, 0, 0); glRotatef(-mouseDragSumX * MOUSE_SENSITIVITY, 0, 1, 0); glRotatef(-90, 0, 0, 1); drawDomeMeshTriangles(&domeV8, &domeMeshV8); glPopMatrix(); glPopMatrix(); }
void CPatchRData::RenderBlends(const std::vector<CPatchRData*>& patches, const CShaderDefines& context, ShadowMap* shadow, bool isDummyShader, const CShaderProgramPtr& dummy) { Allocators::Arena<> arena(ARENA_SIZE); typedef std::vector<SBlendBatch, ProxyAllocator<SBlendBatch, Allocators::Arena<> > > BatchesStack; BatchesStack batches((BatchesStack::allocator_type(arena))); CShaderDefines contextBlend = context; contextBlend.Add("BLEND", "1"); PROFILE_START("compute batches"); // Reserve an arbitrary size that's probably big enough in most cases, // to avoid heavy reallocations batches.reserve(256); typedef std::vector<SBlendStackItem, ProxyAllocator<SBlendStackItem, Allocators::Arena<> > > BlendStacks; BlendStacks blendStacks((BlendStacks::allocator_type(arena))); blendStacks.reserve(patches.size()); // Extract all the blend splats from each patch for (size_t i = 0; i < patches.size(); ++i) { CPatchRData* patch = patches[i]; if (!patch->m_BlendSplats.empty()) { blendStacks.push_back(SBlendStackItem(patch->m_VBBlends, patch->m_VBBlendIndices, patch->m_BlendSplats, arena)); // Reverse the splats so the first to be rendered is at the back of the list std::reverse(blendStacks.back().splats.begin(), blendStacks.back().splats.end()); } } // Rearrange the collection of splats to be grouped by texture, preserving // order of splats within each patch: // (This is exactly the same algorithm used in CPatchRData::BuildBlends, // but applied to patch-sized splats rather than to tile-sized splats; // see that function for comments on the algorithm.) while (true) { if (!batches.empty()) { CTerrainTextureEntry* tex = batches.back().m_Texture; for (size_t k = 0; k < blendStacks.size(); ++k) { SBlendStackItem::SplatStack& splats = blendStacks[k].splats; if (!splats.empty() && splats.back().m_Texture == tex) { CVertexBuffer::VBChunk* vertices = blendStacks[k].vertices; CVertexBuffer::VBChunk* indices = blendStacks[k].indices; BatchElements& batch = PooledPairGet(PooledMapGet(batches.back().m_Batches, vertices->m_Owner, arena), indices->m_Owner, arena); batch.first.push_back(splats.back().m_IndexCount); u8* indexBase = indices->m_Owner->GetBindAddress(); batch.second.push_back(indexBase + sizeof(u16)*(indices->m_Index + splats.back().m_IndexStart)); splats.pop_back(); } } } CTerrainTextureEntry* bestTex = NULL; size_t bestStackSize = 0; for (size_t k = 0; k < blendStacks.size(); ++k) { SBlendStackItem::SplatStack& splats = blendStacks[k].splats; if (splats.size() > bestStackSize) { bestStackSize = splats.size(); bestTex = splats.back().m_Texture; } } if (bestStackSize == 0) break; SBlendBatch layer(arena); layer.m_Texture = bestTex; batches.push_back(layer); } PROFILE_END("compute batches"); CVertexBuffer* lastVB = NULL; for (BatchesStack::iterator itt = batches.begin(); itt != batches.end(); ++itt) { if (itt->m_Texture->GetMaterial().GetSamplers().size() == 0) continue; int numPasses = 1; CShaderTechniquePtr techBase; if (!isDummyShader) { techBase = g_Renderer.GetShaderManager().LoadEffect(itt->m_Texture->GetMaterial().GetShaderEffect(), contextBlend, itt->m_Texture->GetMaterial().GetShaderDefines()); numPasses = techBase->GetNumPasses(); } CShaderProgramPtr previousShader; for (int pass = 0; pass < numPasses; ++pass) { if (!isDummyShader) { techBase->BeginPass(pass); TerrainRenderer::PrepareShader(techBase->GetShader(), shadow); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } const CShaderProgramPtr& shader = isDummyShader ? dummy : techBase->GetShader(pass); if (itt->m_Texture) { CMaterial::SamplersVector samplers = itt->m_Texture->GetMaterial().GetSamplers(); size_t samplersNum = samplers.size(); for (size_t s = 0; s < samplersNum; ++s) { CMaterial::TextureSampler &samp = samplers[s]; shader->BindTexture(samp.Name.c_str(), samp.Sampler); } shader->BindTexture("blendTex", itt->m_Texture->m_TerrainAlpha->second.m_hCompositeAlphaMap); itt->m_Texture->GetMaterial().GetStaticUniforms().BindUniforms(shader); #if !CONFIG2_GLES if (isDummyShader) { pglClientActiveTextureARB(GL_TEXTURE0); glMatrixMode(GL_TEXTURE); glLoadMatrixf(itt->m_Texture->GetTextureMatrix()); glMatrixMode(GL_MODELVIEW); } else #endif { float c = itt->m_Texture->GetTextureMatrix()[0]; float ms = itt->m_Texture->GetTextureMatrix()[8]; shader->Uniform("textureTransform", c, ms, -ms, 0.f); } } else { shader->BindTexture("baseTex", g_Renderer.GetTextureManager().GetErrorTexture()); } for (VertexBufferBatches::iterator itv = itt->m_Batches.begin(); itv != itt->m_Batches.end(); ++itv) { // Rebind the VB only if it changed since the last batch if (itv->first != lastVB || shader != previousShader) { lastVB = itv->first; previousShader = shader; GLsizei stride = sizeof(SBlendVertex); SBlendVertex *base = (SBlendVertex *)itv->first->Bind(); shader->VertexPointer(3, GL_FLOAT, stride, &base->m_Position[0]); shader->ColorPointer(4, GL_UNSIGNED_BYTE, stride, &base->m_DiffuseColor); shader->NormalPointer(GL_FLOAT, stride, &base->m_Normal[0]); shader->TexCoordPointer(GL_TEXTURE0, 3, GL_FLOAT, stride, &base->m_Position[0]); shader->TexCoordPointer(GL_TEXTURE1, 2, GL_FLOAT, stride, &base->m_AlphaUVs[0]); } shader->AssertPointersBound(); for (IndexBufferBatches::iterator it = itv->second.begin(); it != itv->second.end(); ++it) { it->first->Bind(); BatchElements& batch = it->second; if (!g_Renderer.m_SkipSubmit) { for (size_t i = 0; i < batch.first.size(); ++i) glDrawElements(GL_TRIANGLES, batch.first[i], GL_UNSIGNED_SHORT, batch.second[i]); } g_Renderer.m_Stats.m_DrawCalls++; g_Renderer.m_Stats.m_BlendSplats++; g_Renderer.m_Stats.m_TerrainTris += std::accumulate(batch.first.begin(), batch.first.end(), 0) / 3; } } if (!isDummyShader) { glDisable(GL_BLEND); techBase->EndPass(); } } } #if !CONFIG2_GLES if (isDummyShader) { pglClientActiveTextureARB(GL_TEXTURE0); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } #endif CVertexBuffer::Unbind(); }
void CVertMeshInstance::Draw(unsigned flags) { guard(CVertMeshInstance::Draw); if (!Sections.Num()) return; // empty mesh int i; // get 2 frames for interpolation int FrameNum1, FrameNum2; float frac; if (AnimIndex != INDEX_NONE) { const FMeshAnimSeq &A = pMesh->AnimSeqs[AnimIndex]; FrameNum1 = appFloor(AnimTime); FrameNum2 = FrameNum1 + 1; if (FrameNum2 >= A.NumFrames) FrameNum2 = 0; frac = AnimTime - FrameNum1; FrameNum1 += A.StartFrame; FrameNum2 += A.StartFrame; // clamp frame numbers (has mesh with wrong frame count in last animation: // UT1/BotPack/cdgunmainM; this animation is shown in UnrealEd as lerping to null size) if (FrameNum1 >= pMesh->FrameCount) FrameNum1 = pMesh->FrameCount-1; if (FrameNum2 >= pMesh->FrameCount) FrameNum2 = pMesh->FrameCount-1; } else { FrameNum1 = 0; FrameNum2 = 0; frac = 0; } int base1 = pMesh->VertexCount * FrameNum1; int base2 = pMesh->VertexCount * FrameNum2; float backLerp = 1 - frac; CVec3 Scale1, Scale2; Scale1 = Scale2 = CVT(pMesh->MeshScale); Scale1.Scale(backLerp); Scale2.Scale(frac); // compute deformed mesh const FMeshWedge *W = &pMesh->Wedges[0]; CVec3 *pVec = Verts; CVec3 *pNormal = Normals; for (i = 0; i < pMesh->Wedges.Num(); i++, pVec++, pNormal++, W++) { CVec3 tmp; #if 0 // path with no frame lerp // vertex const FMeshVert &V = pMesh->Verts[base1 + W->iVertex]; tmp[0] = V.X * pMesh->MeshScale.X; tmp[1] = V.Y * pMesh->MeshScale.Y; tmp[2] = V.Z * pMesh->MeshScale.Z; BaseTransform.TransformPoint(tmp, *pVec); // normal const FMeshNorm &N = pMesh->Normals[base1 + W->iVertex]; tmp[0] = (N.X - 512.0f) / 512; tmp[1] = (N.Y - 512.0f) / 512; tmp[2] = (N.Z - 512.0f) / 512; BaseTransform.axis.TransformVector(tmp, *pNormal); #else // vertex const FMeshVert &V1 = pMesh->Verts[base1 + W->iVertex]; const FMeshVert &V2 = pMesh->Verts[base2 + W->iVertex]; tmp[0] = V1.X * Scale1[0] + V2.X * Scale2[0]; tmp[1] = V1.Y * Scale1[1] + V2.Y * Scale2[1]; tmp[2] = V1.Z * Scale1[2] + V2.Z * Scale2[2]; BaseTransform.TransformPoint(tmp, *pVec); // normal const FMeshNorm &N1 = pMesh->Normals[base1 + W->iVertex]; const FMeshNorm &N2 = pMesh->Normals[base2 + W->iVertex]; tmp[0] = (N1.X * backLerp + N2.X * frac - 512.0f) / 512; tmp[1] = (N1.Y * backLerp + N2.Y * frac - 512.0f) / 512; tmp[2] = (N1.Z * backLerp + N2.Z * frac - 512.0f) / 512; BaseTransform.axis.TransformVector(tmp, *pNormal); #endif } #if 0 glBegin(GL_POINTS); for (i = 0; i < pMesh->Wedges.Num(); i++) { glVertex3fv(Verts[i].v); } glEnd(); return; #endif // draw mesh glEnable(GL_LIGHTING); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(CVec3), Verts); glNormalPointer(GL_FLOAT, sizeof(CVec3), Normals); glTexCoordPointer(2, GL_FLOAT, sizeof(FMeshWedge), &pMesh->Wedges[0].TexUV.U); for (i = 0; i < Sections.Num(); i++) { const CMeshSection &Sec = Sections[i]; if (!Sec.NumFaces) continue; SetMaterial(Sec.Material, i); glDrawElements(GL_TRIANGLES, Sec.NumFaces * 3, GL_UNSIGNED_SHORT, &Indices[Sec.FirstIndex]); } glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisable(GL_LIGHTING); BindDefaultMaterial(true); // draw mesh normals if (flags & DF_SHOW_NORMALS) { glBegin(GL_LINES); glColor3f(0.5, 1, 0); for (i = 0; i < pMesh->Wedges.Num(); i++) { glVertex3fv(Verts[i].v); CVec3 tmp; VectorMA(Verts[i], 2, Normals[i], tmp); glVertex3fv(tmp.v); } glEnd(); } unguard; }
void CPatchRData::RenderStreams(const std::vector<CPatchRData*>& patches, const CShaderProgramPtr& shader, int streamflags) { // Each batch has a list of index counts, and a list of pointers-to-first-indexes typedef std::pair<std::vector<GLint>, std::vector<void*> > BatchElements; // Group batches by index buffer typedef std::map<CVertexBuffer*, BatchElements> IndexBufferBatches; // Group batches by vertex buffer typedef std::map<CVertexBuffer*, IndexBufferBatches> VertexBufferBatches; VertexBufferBatches batches; PROFILE_START("compute batches"); // Collect all the patches into their appropriate batches for (size_t i = 0; i < patches.size(); ++i) { CPatchRData* patch = patches[i]; BatchElements& batch = batches[patch->m_VBBase->m_Owner][patch->m_VBBaseIndices->m_Owner]; batch.first.push_back(patch->m_VBBaseIndices->m_Count); u8* indexBase = patch->m_VBBaseIndices->m_Owner->GetBindAddress(); batch.second.push_back(indexBase + sizeof(u16)*(patch->m_VBBaseIndices->m_Index)); } PROFILE_END("compute batches"); ENSURE(!(streamflags & ~(STREAM_POS|STREAM_COLOR|STREAM_POSTOUV0|STREAM_POSTOUV1))); // Render each batch for (VertexBufferBatches::iterator itv = batches.begin(); itv != batches.end(); ++itv) { GLsizei stride = sizeof(SBaseVertex); SBaseVertex *base = (SBaseVertex *)itv->first->Bind(); shader->VertexPointer(3, GL_FLOAT, stride, &base->m_Position); if (streamflags & STREAM_POSTOUV0) shader->TexCoordPointer(GL_TEXTURE0, 3, GL_FLOAT, stride, &base->m_Position); if (streamflags & STREAM_POSTOUV1) shader->TexCoordPointer(GL_TEXTURE1, 3, GL_FLOAT, stride, &base->m_Position); if (streamflags & STREAM_COLOR) shader->ColorPointer(4, GL_UNSIGNED_BYTE, stride, &base->m_DiffuseColor); shader->AssertPointersBound(); for (IndexBufferBatches::iterator it = itv->second.begin(); it != itv->second.end(); ++it) { it->first->Bind(); BatchElements& batch = it->second; if (!g_Renderer.m_SkipSubmit) { for (size_t i = 0; i < batch.first.size(); ++i) glDrawElements(GL_TRIANGLES, batch.first[i], GL_UNSIGNED_SHORT, batch.second[i]); } g_Renderer.m_Stats.m_DrawCalls++; g_Renderer.m_Stats.m_TerrainTris += std::accumulate(batch.first.begin(), batch.first.end(), 0) / 3; } } CVertexBuffer::Unbind(); }
void CPatchRData::RenderBases(const std::vector<CPatchRData*>& patches, const CShaderDefines& context, ShadowMap* shadow, bool isDummyShader, const CShaderProgramPtr& dummy) { Allocators::Arena<> arena(ARENA_SIZE); TextureBatches batches (TextureBatches::key_compare(), (TextureBatches::allocator_type(arena))); PROFILE_START("compute batches"); // Collect all the patches' base splats into their appropriate batches for (size_t i = 0; i < patches.size(); ++i) { CPatchRData* patch = patches[i]; for (size_t j = 0; j < patch->m_Splats.size(); ++j) { SSplat& splat = patch->m_Splats[j]; BatchElements& batch = PooledPairGet( PooledMapGet( PooledMapGet(batches, splat.m_Texture, arena), patch->m_VBBase->m_Owner, arena ), patch->m_VBBaseIndices->m_Owner, arena ); batch.first.push_back(splat.m_IndexCount); u8* indexBase = patch->m_VBBaseIndices->m_Owner->GetBindAddress(); batch.second.push_back(indexBase + sizeof(u16)*(patch->m_VBBaseIndices->m_Index + splat.m_IndexStart)); } } PROFILE_END("compute batches"); // Render each batch for (TextureBatches::iterator itt = batches.begin(); itt != batches.end(); ++itt) { int numPasses = 1; CShaderTechniquePtr techBase; if (!isDummyShader) { if (itt->first->GetMaterial().GetShaderEffect().length() == 0) { LOGERROR(L"Terrain renderer failed to load shader effect.\n"); continue; } techBase = g_Renderer.GetShaderManager().LoadEffect(itt->first->GetMaterial().GetShaderEffect(), context, itt->first->GetMaterial().GetShaderDefines()); numPasses = techBase->GetNumPasses(); } for (int pass = 0; pass < numPasses; ++pass) { if (!isDummyShader) { techBase->BeginPass(pass); TerrainRenderer::PrepareShader(techBase->GetShader(), shadow); } const CShaderProgramPtr& shader = isDummyShader ? dummy : techBase->GetShader(pass); if (itt->first->GetMaterial().GetSamplers().size() != 0) { CMaterial::SamplersVector samplers = itt->first->GetMaterial().GetSamplers(); size_t samplersNum = samplers.size(); for (size_t s = 0; s < samplersNum; ++s) { CMaterial::TextureSampler &samp = samplers[s]; shader->BindTexture(samp.Name.c_str(), samp.Sampler); } itt->first->GetMaterial().GetStaticUniforms().BindUniforms(shader); #if !CONFIG2_GLES if (isDummyShader) { glMatrixMode(GL_TEXTURE); glLoadMatrixf(itt->first->GetTextureMatrix()); glMatrixMode(GL_MODELVIEW); } else #endif { float c = itt->first->GetTextureMatrix()[0]; float ms = itt->first->GetTextureMatrix()[8]; shader->Uniform("textureTransform", c, ms, -ms, 0.f); } } else { shader->BindTexture("baseTex", g_Renderer.GetTextureManager().GetErrorTexture()); } for (VertexBufferBatches::iterator itv = itt->second.begin(); itv != itt->second.end(); ++itv) { GLsizei stride = sizeof(SBaseVertex); SBaseVertex *base = (SBaseVertex *)itv->first->Bind(); shader->VertexPointer(3, GL_FLOAT, stride, &base->m_Position[0]); shader->ColorPointer(4, GL_UNSIGNED_BYTE, stride, &base->m_DiffuseColor); shader->NormalPointer(GL_FLOAT, stride, &base->m_Normal[0]); shader->TexCoordPointer(GL_TEXTURE0, 3, GL_FLOAT, stride, &base->m_Position[0]); shader->AssertPointersBound(); for (IndexBufferBatches::iterator it = itv->second.begin(); it != itv->second.end(); ++it) { it->first->Bind(); BatchElements& batch = it->second; if (!g_Renderer.m_SkipSubmit) { // Don't use glMultiDrawElements here since it doesn't have a significant // performance impact and it suffers from various driver bugs (e.g. it breaks // in Mesa 7.10 swrast with index VBOs) for (size_t i = 0; i < batch.first.size(); ++i) glDrawElements(GL_TRIANGLES, batch.first[i], GL_UNSIGNED_SHORT, batch.second[i]); } g_Renderer.m_Stats.m_DrawCalls++; g_Renderer.m_Stats.m_TerrainTris += std::accumulate(batch.first.begin(), batch.first.end(), 0) / 3; } } if (!isDummyShader) techBase->EndPass(); } } #if !CONFIG2_GLES if (isDummyShader) { glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } #endif CVertexBuffer::Unbind(); }
static void pie_Draw3DShape2(const iIMDShape *shape, int frame, PIELIGHT colour, PIELIGHT teamcolour, int pieFlag, int pieFlagData, glm::mat4 const &matrix) { bool light = true; glLoadMatrixf(&matrix[0][0]); /* Set fog status */ if (!(pieFlag & pie_FORCE_FOG) && (pieFlag & pie_ADDITIVE || pieFlag & pie_TRANSLUCENT || pieFlag & pie_PREMULTIPLIED)) { pie_SetFogStatus(false); } else { pie_SetFogStatus(true); } /* Set tranlucency */ if (pieFlag & pie_ADDITIVE) { pie_SetRendMode(REND_ADDITIVE); colour.byte.a = (UBYTE)pieFlagData; light = false; } else if (pieFlag & pie_TRANSLUCENT) { pie_SetRendMode(REND_ALPHA); colour.byte.a = (UBYTE)pieFlagData; light = false; } else if (pieFlag & pie_PREMULTIPLIED) { pie_SetRendMode(REND_PREMULTIPLIED); light = false; } else { pie_SetRendMode(REND_OPAQUE); } if (pieFlag & pie_ECM) { pie_SetRendMode(REND_ALPHA); light = true; pie_SetShaderEcmEffect(true); } SHADER_MODE mode = shape->shaderProgram == SHADER_NONE ? light ? SHADER_COMPONENT : SHADER_NOLIGHT : shape->shaderProgram; SHADER_PROGRAM &program = pie_ActivateShader(mode, shape, teamcolour, colour); glUniform1i(program.locAlphaTest, (pieFlag & pie_PREMULTIPLIED) == 0); pie_SetTexturePage(shape->texpage); frame %= std::max<int>(1, shape->numFrames); enableArray(shape->buffers[VBO_VERTEX], program.locVertex, 3, GL_FLOAT, false, 0, 0); enableArray(shape->buffers[VBO_NORMAL], program.locNormal, 3, GL_FLOAT, false, 0, 0); enableArray(shape->buffers[VBO_TEXCOORD], program.locTexCoord, 2, GL_FLOAT, false, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, shape->buffers[VBO_INDEX]); glDrawElements(GL_TRIANGLES, shape->npolys * 3, GL_UNSIGNED_SHORT, BUFFER_OFFSET(frame * shape->npolys * 3 * sizeof(uint16_t))); disableArrays(); polyCount += shape->npolys; pie_SetShaderEcmEffect(false); }
int main() { //窗口管理,初始化和设置 glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//OpenGL 使用核心模式 glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);//窗口大小不可变 //创建一个窗口 GLFWwindow* window = glfwCreateWindow(800, 600, "HelloWindow", nullptr, nullptr); if (window == nullptr) { std::cout << "failed to create window" << std::endl; glfwTerminate(); return -1; } //设置上下文 glfwMakeContextCurrent(window); //可以在创建窗口之后和游戏循环之前注册各种回调函数 glfwSetKeyCallback(window, key_callback); //glew用来管理OpenGL的函数指针 glewExperimental = GL_TRUE; //设置为true是为了让GLEW在管理OpenGL的函数指针时更多地使用现代化技术,设置为false, if (glewInit() != GLEW_OK) { std::cout << "failed to init glew!" << std::endl; return -1; } glViewport(0, 0, 800, 600); //shader GLuint programID = shader::LoadShaders("v.s", "f.s"); //设置顶点数据,位置,颜色,法向等属性 GLfloat vertices[] = { 0.5f,0.5f,0.0f,//右上角 0.5f,-0.5f,0.0f,//右下角 -0.5f,-0.5f,0.0f,//左下角 -0.5f,0.5f,0.0f//左上角 }; GLuint indices[] = {//起始于0 0,1,3,//第一个三角形 1,2,3//第二个三角形 }; GLuint VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); //1.先绑定顶点数组对象(VAO),然后绑定顶点缓存对象(VBO)和属性指针(attribute pointer) glBindVertexArray(VAO); //2.绑定VBO glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //3.绑定EBO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); //4. 设置顶点属性 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glEnableVertexAttribArray(0); //在使用glVertexAttribPointer之后,VBO就是当前上下文绑定对象,所以现在我们可以进行解绑操作 glBindBuffer(GL_ARRAY_BUFFER, 0); //5. 解绑VAO,用完VAO之后解绑是一个好的习惯 glBindVertexArray(0); //没有while循环的时候窗口闪关,while循环也称游戏循环,在GLFW退出之前一直保持运行 while (!glfwWindowShouldClose(window)) { //检查有没有触发什么事件,如:鼠标移动,调用相应回调函数 glfwPollEvents(); //glClearColor是状态设置函数,设置要清空缓冲的颜色 glClearColor(0.2f, 0.3f, 0.3f, 1.0f); //glClear是状态应用函数,整个指定清空的缓冲区都被填充glClearColor所设置的颜色 glClear(GL_COLOR_BUFFER_BIT); //画三角形 glUseProgram(programID); glBindVertexArray(VAO); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);//线框模式 //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //填充模式 glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); //交换缓冲区(储存着GLFW窗口每一个像素颜色的缓冲区) glfwSwapBuffers(window); } //循环结束后,释放所有资源 glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glfwTerminate(); //释放GLFW分配的内存 return 0; }
/** * @brief Draws weather effects */ void Weather::render (void) { /* Don't play the weather particles if the user doesn't want them */ if (!Cvar_GetInteger("cl_particleweather")) { return; } GLfloat prtPos[3 * 4 * Weather::MAX_PARTICLES]; GLfloat prtTexcoord[2 * 4 * Weather::MAX_PARTICLES]; GLushort prtIndex[3 * 2 * Weather::MAX_PARTICLES]; size_t prtCount = 0; //const float splashTimeScale = 0.001f / splashTime; /* from msec to 1/sec units, so division is done only once per frame */ /** @todo shadowcasting at least for the sunlight */ #if 0 // disabled because of bizarre colors vec4_t prtColor = {color[0] * (refdef.ambientColor[0] + refdef.sunDiffuseColor[0]), color[1] * (refdef.ambientColor[1] + refdef.sunDiffuseColor[1]), color[2] * (refdef.ambientColor[2] + refdef.sunDiffuseColor[2]), color[3]}; #else vec_t prtBrightness = VectorLength(refdef.ambientColor) + VectorLength(refdef.sunDiffuseColor); /** @todo proper color to brightness mapping */ vec4_t prtColor = {color[0] * prtBrightness, color[1] * prtBrightness, color[2] * prtBrightness, color[3]}; /* alpha is not to be scaled */ #endif for (size_t i = 0; i < Weather::MAX_PARTICLES; i++) { Weather::particle &prt = particles[i]; if (prt.ttl < 0) continue; /* if particle is alive, construct a camera-facing quad */ GLfloat x, y, z; GLfloat dx, dy, dz; GLfloat thisParticleSize = particleSize; if (prt.vz == 0 && splashTime > 0) { /* splash particle, do zoom and other things */ /** @todo alpha decay */ const float splashFactor = prt.ttl / 500.0f;//1.0f - prt.ttl * splashTimeScale; thisParticleSize *= (splashSize - 1.0f) * splashFactor + 1.0f; dx = dy = thisParticleSize; } else { dx = i & 1 ? thisParticleSize* 2 : thisParticleSize; dy = i & 1 ? thisParticleSize : thisParticleSize * 2 ; /** @todo make a proper projection instead of this hack */ } x = prt.x; y = prt.y; z = prt.z; dz = smearLength * prt.vz * 0.5; /** @todo should use proper velocity vector ... or maybe not */ /* construct a particle geometry; */ GLfloat *pos = &prtPos[3 * 4 * prtCount]; GLfloat *texcoord = &prtTexcoord[2 * 4 * prtCount]; GLushort *idx = &prtIndex[3 * 2 * prtCount]; /** @todo actually rotate billboard in the correct position */ pos[0] = x - dx; pos[1] = y - dy; pos[2] = z + dz * 2; pos[3] = x + dx; pos[4] = y - dy; pos[5] = z + dz *2; pos[6] = x + dx; pos[7] = y + dy; pos[8] = z; pos[9] = x - dx; pos[10] = y + dy; pos[11] = z; texcoord[0] = 0; texcoord[1] = 0; /* upper left vertex */ texcoord[2] = 1.0f; texcoord[3] = 0; /* upper right vertex */ texcoord[4] = 1.0f; texcoord[5] = 1.0f; /* bottom right vertex */ texcoord[6] = 0; texcoord[7] = 1.0f; /* bottom left vertex */ idx[0] = 4 * prtCount; idx[1] = 4 * prtCount + 1; idx[2] = 4 * prtCount + 2; idx[3] = 4 * prtCount + 2; idx[4] = 4 * prtCount + 3; idx[5] = 4 * prtCount; prtCount++; } if (prtCount < 1) return; /* draw the generated array */ R_Color(prtColor); glBindTexture(GL_TEXTURE_2D, wpTexture()); R_BindArray(GL_VERTEX_ARRAY, GL_FLOAT, prtPos); R_BindArray(GL_TEXTURE_COORD_ARRAY, GL_FLOAT, prtTexcoord); R_EnableBlend(true); glDrawElements(GL_TRIANGLES, prtCount * 3 * 2, GL_UNSIGNED_SHORT, prtIndex); R_EnableBlend(false); R_ResetArrayState(); R_Color(nullptr); refdef.batchCount++; }
/*!**************************************************************************** @Function DrawMesh @Input i32NodeIndex Node index of the mesh to draw @Description Draws a SPODMesh after the model view matrix has been set and the meterial prepared. ******************************************************************************/ void OGLES3PVRScopeRemote::DrawMesh(int i32NodeIndex) { CPPLProcessingScoped PPLProcessingScoped(m_psSPSCommsData, __FUNCTION__, static_cast<unsigned int>(strlen(__FUNCTION__)), m_i32FrameCounter); int i32MeshIndex = m_Scene.pNode[i32NodeIndex].nIdx; SPODMesh* pMesh = &m_Scene.pMesh[i32MeshIndex]; // bind the VBO for the mesh glBindBuffer(GL_ARRAY_BUFFER, m_puiVbo[i32MeshIndex]); // bind the index buffer, won't hurt if the handle is 0 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_puiIndexVbo[i32MeshIndex]); // Enable the vertex attribute arrays glEnableVertexAttribArray(VERTEX_ARRAY); glEnableVertexAttribArray(NORMAL_ARRAY); glEnableVertexAttribArray(TEXCOORD_ARRAY); // Set the vertex attribute offsets glVertexAttribPointer(VERTEX_ARRAY, 3, GL_FLOAT, GL_FALSE, pMesh->sVertex.nStride, pMesh->sVertex.pData); glVertexAttribPointer(NORMAL_ARRAY, 3, GL_FLOAT, GL_FALSE, pMesh->sNormals.nStride, pMesh->sNormals.pData); glVertexAttribPointer(TEXCOORD_ARRAY, 2, GL_FLOAT, GL_FALSE, pMesh->psUVW[0].nStride, pMesh->psUVW[0].pData); /* The geometry can be exported in 4 ways: - Indexed Triangle list - Non-Indexed Triangle list - Indexed Triangle strips - Non-Indexed Triangle strips */ if(pMesh->nNumStrips == 0) { if(m_puiIndexVbo[i32MeshIndex]) { // Indexed Triangle list glDrawElements(GL_TRIANGLES, pMesh->nNumFaces*3, GL_UNSIGNED_SHORT, 0); } else { // Non-Indexed Triangle list glDrawArrays(GL_TRIANGLES, 0, pMesh->nNumFaces*3); } } else { for(int i = 0; i < (int)pMesh->nNumStrips; ++i) { int offset = 0; if(m_puiIndexVbo[i32MeshIndex]) { // Indexed Triangle strips glDrawElements(GL_TRIANGLE_STRIP, pMesh->pnStripLength[i]+2, GL_UNSIGNED_SHORT, (GLshort*)(offset*2)); } else { // Non-Indexed Triangle strips glDrawArrays(GL_TRIANGLE_STRIP, offset, pMesh->pnStripLength[i]+2); } offset += pMesh->pnStripLength[i]+2; } } // Safely disable the vertex attribute arrays glDisableVertexAttribArray(VERTEX_ARRAY); glDisableVertexAttribArray(NORMAL_ARRAY); glDisableVertexAttribArray(TEXCOORD_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); }
int main( int argc, char **argv ) { int width = 1024, height=768; float widthf = (float) width, heightf = (float) height; double t; float fps = 0.f; // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); exit( EXIT_FAILURE ); } // Force core profile on Mac OSX #ifdef __APPLE__ glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif // Open a window and create its OpenGL context if( !glfwOpenWindow( width, height, 0,0,0,0, 24, 0, GLFW_WINDOW ) ) { fprintf( stderr, "Failed to open GLFW window\n" ); glfwTerminate(); exit( EXIT_FAILURE ); } glfwSetWindowTitle( "002_forward_a" ); // Core profile is flagged as experimental in glew #ifdef __APPLE__ glewExperimental = GL_TRUE; #endif GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit( EXIT_FAILURE ); } // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); // Enable vertical sync (on cards that support it) glfwSwapInterval( 1 ); GLenum glerr = GL_NO_ERROR; glerr = glGetError(); if (!imguiRenderGLInit(DroidSans_ttf, DroidSans_ttf_len)) { fprintf(stderr, "Could not init GUI renderer.\n"); exit(EXIT_FAILURE); } // Init viewer structures Camera camera; camera_defaults(camera); GUIStates guiStates; init_gui_states(guiStates); // GUI float intensity = 1.0; // Load images and upload textures GLuint textures[3]; glGenTextures(3, textures); int x; int y; int comp; unsigned char * diffuse = stbi_load("textures/spnza_bricks_a_diff.tga", &x, &y, &comp, 3); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, x, y, 0, GL_RGB, GL_UNSIGNED_BYTE, diffuse); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); fprintf(stderr, "Diffuse %dx%d:%d\n", x, y, comp); unsigned char * spec = stbi_load("textures/spnza_bricks_a_spec.tga", &x, &y, &comp, 1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, x, y, 0, GL_RED, GL_UNSIGNED_BYTE, spec); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); fprintf(stderr, "Spec %dx%d:%d\n", x, y, comp); // Try to load and compile shader ShaderGLSL shader; const char * shaderFile = "002/1.glsl"; //int status = load_shader_from_file(shader, shaderFile, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER | ShaderGLSL::GEOMETRY_SHADER); int status = load_shader_from_file(shader, shaderFile, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER); if ( status == -1 ) { fprintf(stderr, "Error on loading %s\n", shaderFile); exit( EXIT_FAILURE ); } // Apply shader GLuint program = shader.program; glUseProgram(program); GLuint projectionLocation = glGetUniformLocation(program, "Projection"); GLuint viewLocation = glGetUniformLocation(program, "View"); GLuint objectLocation = glGetUniformLocation(program, "Object"); GLuint timeLocation = glGetUniformLocation(program, "Time"); GLuint diffuseLocation = glGetUniformLocation(program, "Diffuse"); GLuint specLocation = glGetUniformLocation(program, "Spec"); GLuint intensityLocation = glGetUniformLocation(program, "Intensity"); GLuint cameraPositionLocation = glGetUniformLocation(program, "CameraPosition"); GLuint lightPositionLocation = glGetUniformLocation(program, "LightPosition"); GLuint lightIntensityLocation = glGetUniformLocation(program, "LightIntensity"); GLuint diffuseColorLocation = glGetUniformLocation(program, "DiffuseColor"); GLuint specularColorLocation = glGetUniformLocation(program, "SpecularColor"); GLuint specularFactorLocation = glGetUniformLocation(program, "SpecularFactor"); GLuint lightPositionLocation2 = glGetUniformLocation(program, "LightPosition2"); GLuint lightIntensityLocation2 = glGetUniformLocation(program, "LightIntensity2"); GLuint diffuseColorLocation2 = glGetUniformLocation(program, "DiffuseColor2"); GLuint specularColorLocation2 = glGetUniformLocation(program, "SpecularColor2"); GLuint specularFactorLocation2 = glGetUniformLocation(program, "SpecularFactor2"); GLuint spotLightExternalAngleLocation = glGetUniformLocation(program, "SpotLightExternalAngle"); GLuint spotLightInternalAngleLocation = glGetUniformLocation(program, "SpotLightInternalAngle"); // Load geometry int cube_triangleCount = 12; int cube_triangleList[] = {0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9, 10, 10, 9, 11, 12, 13, 14, 14, 13, 15, 16, 17, 18, 19, 17, 20, 21, 22, 23, 24, 25, 26, }; float cube_uvs[] = {0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f, }; float cube_vertices[] = {-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5 }; float cube_normals[] = {0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, }; int plane_triangleCount = 2; int plane_triangleList[] = {0, 1, 2, 2, 1, 3}; float plane_uvs[] = {0.f, 0.f, 0.f, 10.f, 10.f, 0.f, 10.f, 10.f}; float plane_vertices[] = {-50.0, -1.0, 50.0, 50.0, -1.0, 50.0, -50.0, -1.0, -50.0, 50.0, -1.0, -50.0}; float plane_normals[] = {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0}; // Vertex Array Object GLuint vao[2]; glGenVertexArrays(2, vao); // Vertex Buffer Objects GLuint vbo[8]; glGenBuffers(8, vbo); // Cube glBindVertexArray(vao[0]); // Bind indices and upload data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_triangleList), cube_triangleList, GL_STATIC_DRAW); // Bind vertices and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW); // Bind normals and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[2]); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_normals), cube_normals, GL_STATIC_DRAW); // Bind uv coords and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[3]); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_uvs), cube_uvs, GL_STATIC_DRAW); // Plane glBindVertexArray(vao[1]); // Bind indices and upload data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[4]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(plane_triangleList), plane_triangleList, GL_STATIC_DRAW); // Bind vertices and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[5]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(plane_vertices), plane_vertices, GL_STATIC_DRAW); // Bind normals and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[6]); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(plane_normals), plane_normals, GL_STATIC_DRAW); // Bind uv coords and upload data glBindBuffer(GL_ARRAY_BUFFER, vbo[7]); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0); glBufferData(GL_ARRAY_BUFFER, sizeof(plane_uvs), plane_uvs, GL_STATIC_DRAW); // Unbind everything. Potentially illegal on some implementations glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // Viewport glViewport( 0, 0, width, height ); // Default states glm::vec3 lightPosition(0.0, 1.0, 10); float lightIntensity = 1.0f; glm::vec3 diffuseColor(1.0, 1.0, 1.0); glm::vec3 specularColor(1.0, 1.0, 1.0); float specularFactor = 100.f; glm::vec3 lightPosition2(1.0, 0.0, 10); float lightIntensity2 = 1.0f; glm::vec3 diffuseColor2(1.0, 0.0, 0.0); glm::vec3 specularColor2(1.0, 1.0, 1.0); float specularFactor2 = 100.f; float spotLightInternal = M_PI/32; float spotLightExternal = M_PI/16; bool checkedLight1 = true; bool checkedLight2 = false; bool checkedLight3 = false; do { t = glfwGetTime(); glEnable(GL_DEPTH_TEST); // Mouse states int leftButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT ); int rightButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_RIGHT ); int middleButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_MIDDLE ); if( leftButton == GLFW_PRESS ) guiStates.turnLock = true; else guiStates.turnLock = false; if( rightButton == GLFW_PRESS ) guiStates.zoomLock = true; else guiStates.zoomLock = false; if( middleButton == GLFW_PRESS ) guiStates.panLock = true; else guiStates.panLock = false; // Camera movements int altPressed = glfwGetKey(GLFW_KEY_LSHIFT); if (!altPressed && (leftButton == GLFW_PRESS || rightButton == GLFW_PRESS || middleButton == GLFW_PRESS)) { int x; int y; glfwGetMousePos(&x, &y); guiStates.lockPositionX = x; guiStates.lockPositionY = y; } if (altPressed == GLFW_PRESS) { int mousex; int mousey; glfwGetMousePos(&mousex, &mousey); int diffLockPositionX = mousex - guiStates.lockPositionX; int diffLockPositionY = mousey - guiStates.lockPositionY; if (guiStates.zoomLock) { float zoomDir = 0.0; if (diffLockPositionX > 0) zoomDir = -1.f; else if (diffLockPositionX < 0 ) zoomDir = 1.f; camera_zoom(camera, zoomDir * GUIStates::MOUSE_ZOOM_SPEED); } else if (guiStates.turnLock) { camera_turn(camera, diffLockPositionY * GUIStates::MOUSE_TURN_SPEED, diffLockPositionX * GUIStates::MOUSE_TURN_SPEED); } else if (guiStates.panLock) { camera_pan(camera, diffLockPositionX * GUIStates::MOUSE_PAN_SPEED, diffLockPositionY * GUIStates::MOUSE_PAN_SPEED); } guiStates.lockPositionX = mousex; guiStates.lockPositionY = mousey; } // Get camera matrices glm::mat4 projection = glm::perspective(45.0f, widthf / heightf, 0.1f, 100.f); glm::mat4 worldToView = glm::lookAt(camera.eye, camera.o, camera.up); glm::mat4 objectToWorld; // Clear the front buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Bind textures glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); // Bind shader glUseProgram(program); // Upload uniforms glUniformMatrix4fv(projectionLocation, 1, 0, glm::value_ptr(projection)); glUniformMatrix4fv(viewLocation, 1, 0, glm::value_ptr(worldToView)); glUniformMatrix4fv(objectLocation, 1, 0, glm::value_ptr(objectToWorld)); glUniform1f(timeLocation, t); glUniform3fv(cameraPositionLocation, 1, glm::value_ptr(camera.eye)); glUniform1f(intensityLocation, intensity); glUniform1i(diffuseLocation, 0); glUniform1i(specLocation, 1); glUniform3fv(lightPositionLocation, 1, glm::value_ptr(lightPosition)); glUniform1f(lightIntensityLocation, lightIntensity); glUniform3fv(diffuseColorLocation, 1, glm::value_ptr(diffuseColor)); glUniform3fv(specularColorLocation, 1, glm::value_ptr(specularColor)); glUniform1f(specularFactorLocation, specularFactor); glUniform3fv(lightPositionLocation2, 1, glm::value_ptr(lightPosition2)); glUniform1f(lightIntensityLocation2, lightIntensity2); glUniform3fv(diffuseColorLocation2, 1, glm::value_ptr(diffuseColor2)); glUniform3fv(specularColorLocation2, 1, glm::value_ptr(specularColor2)); glUniform1f(specularFactorLocation2, specularFactor2); glUniform1f(spotLightInternalAngleLocation, spotLightInternal); glUniform1f(spotLightExternalAngleLocation, spotLightExternal); // Render vaos glBindVertexArray(vao[0]); glDrawElementsInstanced(GL_TRIANGLES, cube_triangleCount * 3, GL_UNSIGNED_INT, (void*)0, 4); glBindVertexArray(vao[1]); glDrawElements(GL_TRIANGLES, plane_triangleCount * 3, GL_UNSIGNED_INT, (void*)0); #if 1 // Draw UI glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glViewport(0, 0, width, height); unsigned char mbut = 0; int mscroll = 0; int mousex; int mousey; glfwGetMousePos(&mousex, &mousey); mousey = height - mousey; if( leftButton == GLFW_PRESS ) mbut |= IMGUI_MBUT_LEFT; imguiBeginFrame(mousex, mousey, mbut, mscroll); int logScroll = 0; char lineBuffer[512]; imguiBeginScrollArea("001", 0, 0, 200, height, &logScroll); sprintf(lineBuffer, "FPS %f", fps); imguiLabel(lineBuffer); int toggle = 0; toggle = imguiCollapse("Light1", "", checkedLight1); if(checkedLight1) { imguiIndent(); imguiIndent(); imguiLabel("Light Position"); imguiIndent(); imguiSlider("x", &lightPosition.x, -10, 10, 0.01); imguiSlider("y", &lightPosition.y, -10, 10, 0.01); imguiSlider("z", &lightPosition.z, -10, 10, 0.01); imguiUnindent(); imguiSlider("Light Intensity", &lightIntensity, 0, 3, 0.01); imguiLabel("Diffuse Color"); imguiIndent(); imguiSlider("r", &diffuseColor.x, 0, 1, 0.001); imguiSlider("g", &diffuseColor.y, 0, 1, 0.001); imguiSlider("b", &diffuseColor.z, 0, 1, 0.001); imguiUnindent(); imguiLabel("Specular Color"); imguiIndent(); imguiSlider("r", &specularColor.x, 0, 1, 0.001); imguiSlider("g", &specularColor.y, 0, 1, 0.001); imguiSlider("b", &specularColor.z, 0, 1, 0.001); imguiUnindent(); imguiSlider("Specular Intensity", &specularFactor, 0, 100, 1); imguiUnindent(); imguiUnindent(); } if (toggle) { checkedLight1 = !checkedLight1; } toggle = imguiCollapse("Light2", "", checkedLight2); if(checkedLight2) { imguiIndent(); imguiIndent(); imguiLabel("Light Position"); imguiIndent(); imguiSlider("x", &lightPosition2.x, -10, 10, 0.01); imguiSlider("y", &lightPosition2.y, -10, 10, 0.01); imguiSlider("z", &lightPosition2.z, -10, 10, 0.01); imguiUnindent(); imguiSlider("Light Intensity", &lightIntensity2, 0, 3, 0.01); imguiLabel("Diffuse Color"); imguiIndent(); imguiSlider("r", &diffuseColor2.x, 0, 1, 0.001); imguiSlider("g", &diffuseColor2.y, 0, 1, 0.001); imguiSlider("b", &diffuseColor2.z, 0, 1, 0.001); imguiUnindent(); imguiLabel("Specular Color"); imguiIndent(); imguiSlider("r", &specularColor2.x, 0, 1, 0.001); imguiSlider("g", &specularColor2.y, 0, 1, 0.001); imguiSlider("b", &specularColor2.z, 0, 1, 0.001); imguiUnindent(); imguiSlider("Specular Intensity", &specularFactor2, 0, 100, 1); imguiUnindent(); imguiUnindent(); } if (toggle) { checkedLight2 = !checkedLight2; } toggle = imguiCollapse("SpotLight", "", checkedLight3); if(checkedLight3) { imguiIndent(); imguiIndent(); imguiSlider("External Angle", &spotLightExternal, 0, 2, 0.01); imguiSlider("Internal Angle", &spotLightInternal, 0, 2, 0.01); imguiUnindent(); imguiUnindent(); } if (toggle) { checkedLight3 = !checkedLight3; } imguiEndScrollArea(); imguiEndFrame(); imguiRenderGLDraw(width, height); glDisable(GL_BLEND); #endif // Check for errors GLenum err = glGetError(); if(err != GL_NO_ERROR) { fprintf(stderr, "OpenGL Error : %s\n", gluErrorString(err)); } // Swap buffers glfwSwapBuffers(); } // Check if the ESC key was pressed or the window was closed while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS && glfwGetWindowParam( GLFW_OPENED ) ); // Clean UI imguiRenderGLDestroy(); // Close OpenGL window and terminate GLFW glfwTerminate(); exit( EXIT_SUCCESS ); }
void draw_mesh(t_draw *draw, t_scene *scene, t_mesh *mesh) { t_node *node; t_texture *texture=NULL; // BUFFERS if(mesh->state.buffer_type!=buffer_vbo) mesh_init_buffers(mesh,buffer_vbo); float *color=draw->front_color; // TEXTURE if(draw->with_texture && mesh->state.with_texture) { node = scene_get_node_by_type_name( scene, dt_texture, mesh->texture_name); texture = ( t_texture *) node->data; if(texture && mesh->quad_uv) { glEnable(GL_TEXTURE_2D); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer( 2, GL_INT, 0, mesh->quad_uv->data); glBindTexture(GL_TEXTURE_2D,texture->id_gl); } } // MATERIAL if (draw->with_material) { t_material *material = mesh->material; if(material) { float color[4]; color[0]=material->color[0]; color[1]=material->color[1]; color[2]=material->color[2]; color[3]=material->color[3]; glMaterialfv(GL_FRONT,GL_SPECULAR, mesh->material->specular); glMaterialfv(GL_FRONT,GL_SHININESS, mesh->material->shininess); glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE, color); } } // vertex arrays glEnableClientState(GL_VERTEX_ARRAY); glShadeModel(GL_FLAT); // draw node // SELECTION MODE for drawing wire cube to solid cube if(draw->mode==mode_selection) { if (draw->with_light) { glEnable(GL_LIGHTING); GLfloat model_ambient[] = {1,1,1,1}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT,model_ambient); } // quads //if (mesh->quad_faces && mesh->state.has_quad) if (mesh->state.has_quad) { glVertexPointer(3,GL_FLOAT,0,(float *)mesh->quad_vertex->data); if(mesh->quad_normal && draw->with_normal) glNormalPointer(GL_FLOAT,0,mesh->quad_normal->data); if(mesh->quad_color && draw->mode==mode_selection) glColorPointer(3,GL_FLOAT,0,mesh->quad_color->data); if(mesh->quad_face) glDrawElements(GL_QUADS,mesh->var.tot_quad_face*4,GL_UNSIGNED_INT,mesh->quad_face->data); } // triangles if(mesh->state.has_tri) { glVertexPointer(3,GL_FLOAT,0,(float *)mesh->tri_vertex->data); if(mesh->tri_normal && draw->with_normal) glNormalPointer(GL_FLOAT,0,mesh->tri_normal->data); if(mesh->tri_color && draw->mode==mode_selection) glColorPointer(3,GL_FLOAT,0,mesh->tri_color->data); if(mesh->tri_face) glDrawElements(GL_TRIANGLES,mesh->var.tot_tri_face*3,GL_UNSIGNED_INT,mesh->tri_face->data); } } // DRAW MODE draw faces else if(draw->with_face && mesh->state.has_face) { if (draw->with_light) { glEnable(GL_LIGHTING); GLfloat model_ambient[] = {1,1,1,1}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT,model_ambient); } if(draw->mode==mode_selection) glEnableClientState(GL_COLOR_ARRAY); if(draw->with_normal) glEnableClientState(GL_NORMAL_ARRAY); // quads if (mesh->state.has_quad) { glVertexPointer(3,GL_FLOAT,0,(float *)mesh->quad_vertex->data); if(mesh->quad_normal && draw->with_normal) glNormalPointer(GL_FLOAT,0,mesh->quad_normal->data); if(mesh->quad_color && draw->mode==mode_selection) glColorPointer(3,GL_FLOAT,0,mesh->quad_color->data); if(mesh->quad_face) glDrawElements(GL_QUADS,mesh->var.tot_quad_face*4,GL_UNSIGNED_INT,mesh->quad_face->data); } // triangles if(mesh->state.has_tri) { if (mesh->tri_vertex) { glVertexPointer(3,GL_FLOAT,0,mesh->tri_vertex->data); if(mesh->tri_normal && draw->with_normal) glNormalPointer(GL_FLOAT,0,mesh->tri_normal->data); if(mesh->tri_color && draw->mode==mode_selection) glColorPointer(3,GL_FLOAT,0,mesh->tri_color->data);//XXX if(mesh->tri_face) glDrawElements(GL_TRIANGLES,mesh->var.tot_tri_face*3,GL_UNSIGNED_INT,mesh->tri_face->data); } } } // edges if(mesh->state.with_line) draw_mesh_edge( draw, mesh); // outline if( mesh->state.is_selected && draw->mode == mode_draw && draw->with_face) { if(mesh->state.has_face) { glDisable(GL_LIGHTING); glPushAttrib( GL_ALL_ATTRIB_BITS ); glEnable( GL_POLYGON_OFFSET_FILL ); glPolygonOffset( -2.5f, -2.5f ); glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glLineWidth( 4.0f ); glColor3f(color[0],color[1],color[2]); if(mesh->state.has_quad) glDrawElements(GL_QUADS,mesh->var.tot_quad_face*4,GL_UNSIGNED_INT,mesh->quad_face->data); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glEnable( GL_LIGHTING ); glColor3f( 0.0f, 0.0f, 0.0f ); if(mesh->state.has_quad) glDrawElements(GL_QUADS,mesh->var.tot_quad_face*4,GL_UNSIGNED_INT,mesh->quad_face->data); glPopAttrib(); } } // unbind texture if(texture) glBindTexture(GL_TEXTURE_2D,0); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); // Points if(draw->with_point) { draw_mesh_points(draw,mesh); } }
void BatchedSprite::render_static() { if (_texture_program != NULL) { _texture_program->bind(); _texture_program->model_view_matrix(glm::mat4()); _texture_program->update_model_view_matrix(); _texture_program->enable_vertex_pointer(); _texture_program->enable_texture_coordinate_pointer(); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo); _texture_program->set_texture_coordinate_pointer(sizeof(TextureData2D), (GLvoid*)offsetof(TextureData2D, texture_coordinate)); _texture_program->set_vertex_pointer(sizeof(TextureData2D), (GLvoid*)offsetof(TextureData2D, position)); glDrawElements(GL_TRIANGLES, _num_indices, GL_UNSIGNED_INT, NULL); _texture_program->disable_vertex_pointer(); _texture_program->disable_texture_coordinate_pointer(); } else if (_font_program != NULL) { _font_program->bind(); _font_program->model_view_matrix(glm::mat4()); _font_program->update_model_view_matrix(); _font_program->enable_vertex_pointer(); _font_program->enable_texture_coordinate_pointer(); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo); _font_program->set_texture_coordinate_pointer(sizeof(TextureData2D), (GLvoid*)offsetof(TextureData2D, texture_coordinate)); _font_program->set_vertex_pointer(sizeof(TextureData2D), (GLvoid*)offsetof(TextureData2D, position)); glDrawElements(GL_TRIANGLES, _num_indices, GL_UNSIGNED_INT, NULL); _font_program->disable_vertex_pointer(); _font_program->disable_texture_coordinate_pointer(); } else if (_primitive_program != NULL) { _primitive_program->bind(); _primitive_program->model_view_matrix(glm::mat4()); _primitive_program->update_model_view_matrix(); _primitive_program->enable_vertex_pointer(); _primitive_program->enable_color_pointer(); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo); _primitive_program->set_color_pointer(sizeof(PrimitiveData2D), (GLvoid*)offsetof(PrimitiveData2D, color)); _primitive_program->set_vertex_pointer(sizeof(PrimitiveData2D), (GLvoid*)offsetof(PrimitiveData2D, position)); glDrawElements(GL_TRIANGLES, _num_indices, GL_UNSIGNED_INT, NULL); _primitive_program->disable_vertex_pointer(); _primitive_program->disable_color_pointer(); } }
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // If text or lines are blurry when integrating ImGui in your engine: // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data) { // We are using the OpenGL fixed pipeline to make the example code simpler to read! // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnable(GL_TEXTURE_2D); //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays) ImGuiIO& io = ImGui::GetIO(); int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Setup viewport, orthographic projection matrix glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // Render command lists #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front(); const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front(); glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, pos))); glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, uv))); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, col))); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer); } idx_buffer += pcmd->ElemCount; } } #undef OFFSETOF // Restore modified state glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindTexture(GL_TEXTURE_2D, last_texture); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); }
void RenderableBoxEntityItem::render(RenderArgs* args) { PerformanceTimer perfTimer("RenderableBoxEntityItem::render"); assert(getType() == EntityTypes::Box); glm::vec3 position = getPositionInMeters(); glm::vec3 center = getCenter() * (float)TREE_SCALE; glm::vec3 dimensions = getDimensions() * (float)TREE_SCALE; glm::vec3 halfDimensions = dimensions / 2.0f; glm::quat rotation = getRotation(); const bool useGlutCube = true; if (useGlutCube) { glColor3ub(getColor()[RED_INDEX], getColor()[GREEN_INDEX], getColor()[BLUE_INDEX]); glPushMatrix(); glTranslatef(position.x, position.y, position.z); glm::vec3 axis = glm::axis(rotation); glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); glPushMatrix(); glm::vec3 positionToCenter = center - position; glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); glScalef(dimensions.x, dimensions.y, dimensions.z); glutSolidCube(1.0f); glPopMatrix(); glPopMatrix(); } else { static GLfloat vertices[] = { 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1, // v0,v1,v2,v3 (front) 1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1, // v0,v3,v4,v5 (right) 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0,v5,v6,v1 (top) -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1, // v1,v6,v7,v2 (left) -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1, // v7,v4,v3,v2 (bottom) 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 }; // v4,v7,v6,v5 (back) // normal array static GLfloat normals[] = { 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0,v1,v2,v3 (front) 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0,v3,v4,v5 (right) 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0,v5,v6,v1 (top) -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1,v6,v7,v2 (left) 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7,v4,v3,v2 (bottom) 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 }; // v4,v7,v6,v5 (back) // index array of vertex array for glDrawElements() & glDrawRangeElement() static GLubyte indices[] = { 0, 1, 2, 2, 3, 0, // front 4, 5, 6, 6, 7, 4, // right 8, 9,10, 10,11, 8, // top 12,13,14, 14,15,12, // left 16,17,18, 18,19,16, // bottom 20,21,22, 22,23,20 }; // back glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glNormalPointer(GL_FLOAT, 0, normals); glVertexPointer(3, GL_FLOAT, 0, vertices); glColor3ub(getColor()[RED_INDEX], getColor()[GREEN_INDEX], getColor()[BLUE_INDEX]); glPushMatrix(); glTranslatef(position.x, position.y, position.z); glm::vec3 axis = glm::axis(rotation); glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); glPushMatrix(); glm::vec3 positionToCenter = center - position; glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); // we need to do half the size because the geometry in the VBOs are from -1,-1,-1 to 1,1,1 glScalef(halfDimensions.x, halfDimensions.y, halfDimensions.z); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, indices); glPopMatrix(); glPopMatrix(); glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays glDisableClientState(GL_NORMAL_ARRAY); } };
// 0___1___2___3 // | /| /| /| // | / | / | / | // |/ |/ |/ | // 4---5---6----7 // | /| /| /| // | / | / | / | // |/ |/ |/ | // 8---9--10--11 // | /| /| /| // | / | / | / | // |/ |/ |/ | // 12--13--14--15 void ViewerGL::Implementation::drawRenderingVAO(unsigned int mipMapLevel, int textureIndex, ViewerGL::DrawPolygonModeEnum polygonMode, bool background) { // always running in the main thread assert( qApp && qApp->thread() == QThread::currentThread() ); assert( QGLContext::currentContext() == _this->context() ); bool useShader = _this->getBitDepth() != eImageBitDepthByte; ///the texture rectangle in image coordinates. The values in it are multiples of tile size. /// const TextureRect &roiRounded = this->displayTextures[textureIndex].texture->getTextureRect(); const TextureRect& roiNotRounded = this->displayTextures[textureIndex].roiNotRoundedToTileSize; ///This is the coordinates in the image being rendered where datas are valid, this is in pixel coordinates ///at the time we initialize it but we will convert it later to canonical coordinates. See 1) const double par = roiRounded.par; RectD canonicalRoIRoundedToTileSize; roiRounded.toCanonical_noClipping(mipMapLevel, par /*, rod*/, &canonicalRoIRoundedToTileSize); RectD canonicalRoINotRounded; roiNotRounded.toCanonical_noClipping(mipMapLevel, par, &canonicalRoINotRounded); ///the RoD of the image in canonical coords. RectD rod = _this->getRoD(textureIndex); bool clipToDisplayWindow; { QMutexLocker l(&this->clipToDisplayWindowMutex); clipToDisplayWindow = this->clipToDisplayWindow; } RectD rectClippedToRoI(canonicalRoINotRounded); if (clipToDisplayWindow) { RectD canonicalProjectFormat; this->getProjectFormatCanonical(canonicalProjectFormat); rod.intersect(canonicalProjectFormat, &rod); rectClippedToRoI.intersect(canonicalProjectFormat, &rectClippedToRoI); } //if user RoI is enabled, clip the rod to that roi bool userRoiEnabled; { QMutexLocker l(&this->userRoIMutex); userRoiEnabled = this->userRoIEnabled; } ////The texture real size (r.w,r.h) might be slightly bigger than the actual ////pixel coordinates bounds r.x1,r.x2 r.y1 r.y2 because we clipped these bounds against the bounds ////in the ViewerInstance::renderViewer function. That means we need to draw actually only the part of ////the texture that contains the bounds. ////Notice that r.w and r.h are scaled to the closest Po2 of the current scaling factor, so we need to scale it up ////So it is in the same coordinates as the bounds. ///Edit: we no longer divide by the closestPo2 since the viewer now computes images at lower resolution by itself, the drawing ///doesn't need to be scaled. if (userRoiEnabled) { { QMutexLocker l(&this->userRoIMutex); //if the userRoI isn't intersecting the rod, just don't render anything if ( !rod.intersect(this->userRoI, &rod) ) { return; } } rectClippedToRoI.intersect(rod, &rectClippedToRoI); //clipTexCoords<RectD>(canonicalTexRect,rectClippedToRoI,texBottom,texTop,texLeft,texRight); } if (polygonMode != eDrawPolygonModeWhole) { /// draw only the plane defined by the wipe handle QPolygonF polygonPoints, polygonTexCoords; RectD floatRectClippedToRoI; floatRectClippedToRoI.x1 = rectClippedToRoI.x1; floatRectClippedToRoI.y1 = rectClippedToRoI.y1; floatRectClippedToRoI.x2 = rectClippedToRoI.x2; floatRectClippedToRoI.y2 = rectClippedToRoI.y2; Implementation::WipePolygonEnum polyType = this->getWipePolygon(floatRectClippedToRoI, polygonMode == eDrawPolygonModeWipeRight, &polygonPoints); if (polyType == Implementation::eWipePolygonEmpty) { ///don't draw anything return; } else if (polyType == Implementation::eWipePolygonPartial) { this->getPolygonTextureCoordinates(polygonPoints, canonicalRoIRoundedToTileSize, polygonTexCoords); this->bindTextureAndActivateShader(textureIndex, useShader); glBegin(GL_POLYGON); for (int i = 0; i < polygonTexCoords.size(); ++i) { const QPointF & tCoord = polygonTexCoords[i]; const QPointF & vCoord = polygonPoints[i]; glTexCoord2d( tCoord.x(), tCoord.y() ); glVertex2d( vCoord.x(), vCoord.y() ); } glEnd(); this->unbindTextureAndReleaseShader(useShader); } else { ///draw the all polygon as usual polygonMode = eDrawPolygonModeWhole; } } if (polygonMode == eDrawPolygonModeWhole) { const double pixelCenterOffset = 0.5; // draw vertices at the center of the first and last pixel in the texture, with the same texture coordinates rectClippedToRoI.x1 += pixelCenterOffset * par; rectClippedToRoI.x2 -= pixelCenterOffset * par; rectClippedToRoI.y1 += pixelCenterOffset; rectClippedToRoI.y2 -= pixelCenterOffset; ///Vertices are in canonical coords GLfloat vertices[32] = { (GLfloat)rod.left(), (GLfloat)rod.top(), //0 (GLfloat)rectClippedToRoI.x1 + pixelCenterOffset, (GLfloat)rod.top(), //1 (GLfloat)rectClippedToRoI.x2 - pixelCenterOffset, (GLfloat)rod.top(), //2 (GLfloat)rod.right(), (GLfloat)rod.top(), //3 (GLfloat)rod.left(), (GLfloat)rectClippedToRoI.y2 - pixelCenterOffset, //4 (GLfloat)rectClippedToRoI.x1, (GLfloat)rectClippedToRoI.y2, //5 (GLfloat)rectClippedToRoI.x2, (GLfloat)rectClippedToRoI.y2, //6 (GLfloat)rod.right(), (GLfloat)rectClippedToRoI.y2, //7 (GLfloat)rod.left(), (GLfloat)rectClippedToRoI.y1, //8 (GLfloat)rectClippedToRoI.x1, (GLfloat)rectClippedToRoI.y1, //9 (GLfloat)rectClippedToRoI.x2, (GLfloat)rectClippedToRoI.y1, //10 (GLfloat)rod.right(), (GLfloat)rectClippedToRoI.y1, //11 (GLfloat)rod.left(), (GLfloat)rod.bottom(), //12 (GLfloat)rectClippedToRoI.x1, (GLfloat)rod.bottom(), //13 (GLfloat)rectClippedToRoI.x2, (GLfloat)rod.bottom(), //14 (GLfloat)rod.right(), (GLfloat)rod.bottom() //15 }; // GLfloat texBottom = 0; // GLfloat texTop = (GLfloat)(r.y2 - r.y1) / (GLfloat)(r.h /** r.closestPo2*/); // GLfloat texLeft = 0; // GLfloat texRight = (GLfloat)(r.x2 - r.x1) / (GLfloat)(r.w /** r.closestPo2*/); GLfloat texBottom = (GLfloat)(rectClippedToRoI.y1 - canonicalRoIRoundedToTileSize.y1) / canonicalRoIRoundedToTileSize.height(); GLfloat texTop = (GLfloat)(rectClippedToRoI.y2 - canonicalRoIRoundedToTileSize.y1) / canonicalRoIRoundedToTileSize.height(); GLfloat texLeft = (GLfloat)(rectClippedToRoI.x1 - canonicalRoIRoundedToTileSize.x1) / canonicalRoIRoundedToTileSize.width(); GLfloat texRight = (GLfloat)(rectClippedToRoI.x2 - canonicalRoIRoundedToTileSize.x1) / canonicalRoIRoundedToTileSize.width(); GLfloat renderingTextureCoordinates[32] = { texLeft, texTop, //0 texLeft, texTop, //1 texRight, texTop, //2 texRight, texTop, //3 texLeft, texTop, //4 texLeft, texTop, //5 texRight, texTop, //6 texRight, texTop, //7 texLeft, texBottom, //8 texLeft, texBottom, //9 texRight, texBottom, //10 texRight, texBottom, //11 texLeft, texBottom, // 12 texLeft, texBottom, //13 texRight, texBottom, //14 texRight, texBottom //15 }; if ( background && this->viewerTab->isCheckerboardEnabled() && (polygonMode != eDrawPolygonModeWipeRight) ) { bool isblend = glIsEnabled(GL_BLEND); if (isblend) { glDisable(GL_BLEND); } this->drawCheckerboardTexture(rod); if (isblend) { glEnable(GL_BLEND); } } this->bindTextureAndActivateShader(textureIndex, useShader); glCheckError(); glBindBuffer(GL_ARRAY_BUFFER, this->vboVerticesId); glBufferSubData(GL_ARRAY_BUFFER, 0, 32 * sizeof(GLfloat), vertices); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, this->vboTexturesId); glBufferSubData(GL_ARRAY_BUFFER, 0, 32 * sizeof(GLfloat), renderingTextureCoordinates); glClientActiveTexture(GL_TEXTURE0); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, 0); glDisableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->iboTriangleStripId); glDrawElements(GL_TRIANGLE_STRIP, 28, GL_UNSIGNED_BYTE, 0); glCheckErrorIgnoreOSXBug(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glCheckError(); this->unbindTextureAndReleaseShader(useShader); } } // drawRenderingVAO
void CVComplexShape::Draw() { // logToFile((f, "CVComplexShape Draw\n")); if(!m_IsVisible) return; double *vertices = exact ? scrVertices : m_getVertices(); if (arrays[aiIndices] != 0 && GetLength(arrays[aiIndices], 1) == 0 || vertices == 0 || GetLength(vertices, 1) == 0) return; glPushMatrix(); if(exact) { glMatrixMode (GL_MODELVIEW); glLoadIdentity(); glTranslated(0.0, 0.0, m_dZ); } else { // Only get exact calibration location of center // and approximate the rest of the points /* float x = XPosToScreen((float)X,(float)Y); float y = YPosToScreen((float)X,(float)Y); m_nClipped = VISWIN_IS_CLIPPED(x,y); */ float pix[2]; g_TransformCoordinatesF( m_dX, m_dY, pix, pix+1 ); m_nClipped = IS_OFF_WINDOW(pix[0],pix[1]); g_TransformGradientD(JAC,m_dX,m_dY); /* DPosToDScreen(JAC,x,y); */ // Rot 4x4, allocated by column, as in matlab // Jac, though, is only the 2x2 Jacobian ROT[0]=m_dScale*JAC[0][0]; ROT[1]=m_dScale*JAC[1][0]; ROT[4]=m_dScale*JAC[0][1]; ROT[5]=m_dScale*JAC[1][1]; ROT[12]=pix[0]; ROT[13]=pix[1]; ROT[14]=m_dZ; glMatrixMode (GL_MODELVIEW); // glLoadIdentity(); // glTranslatef((float)x,(float)y,Z); // 3: Translate // glScalef((float)scx,(float)scy,1); // 2: Scale glLoadMatrixd(ROT); // 2: Translate and Scale glRotatef((float)m_dAngle,0,0,1); // 1: Rotate About Z axis } glColor4d(m_fRGB[0],m_fRGB[1],m_fRGB[2],m_fAlpha); if (drawMode >= odmLines && drawMode <= odmLineLoop) { if (lineStipple != 0) { glLineStipple(lineStippleFactor, lineStipple); glEnable(GL_LINE_STIPPLE); } if (lineWidth != 1.0) glLineWidth((float)lineWidth); } if (drawMode == odmPoints && pointSize != 1.0) glPointSize((float)pointSize); if (drawMode >= odmTriangles && drawMode <= odmPolygon) { if (arrays[aiPolygonStipple] != 0) { glEnable(GL_POLYGON_STIPPLE); glPolygonStipple((unsigned char *)arrays[aiPolygonStipple]); } } if (vertices != 0) glEnableClientState(GL_VERTEX_ARRAY); if (arrays[aiColors ] != 0) glEnableClientState(GL_COLOR_ARRAY); if (arrays[aiEdgeFlags] != 0) glEnableClientState(GL_EDGE_FLAG_ARRAY); if (arrays[aiIndices] != 0) { if (vertices != 0) glVertexPointer(GetLength(vertices, 0), GL_DOUBLE, 0, vertices); if (arrays[aiColors] != 0) glColorPointer (GetLength(arrays[aiColors], 0), GL_DOUBLE, 0, arrays[aiColors]); // if (arrays[aiEdgeFlags] != 0) // glEdgeFlagPointer(0, arrays[aiEdgeFlags]); if (GetDim(arrays[aiIndices]) == 1 || GetLength(arrays[aiIndices], 0) == 1) glDrawElements(glDrawModeMap[drawMode], GetLength(arrays[aiIndices]), GL_UNSIGNED_INT, arrays[aiIndices]); else { int len0 = GetLength(arrays[aiIndices], 0); int len1 = GetLength(arrays[aiIndices], 1); for (int i=0; i < len1; ++i) glDrawElements(glDrawModeMap[drawMode], len0, GL_UNSIGNED_INT, ((unsigned int *)arrays[aiIndices]) + len0 * i); } } else if (vertices != 0) { int len2 = GetDim(vertices) <= 2 ? 1 : GetLength(vertices, 2); for (int i=0; i < len2; ++i) { if (vertices != 0) glVertexPointer(GetLength(vertices, 0), GL_DOUBLE, 0, vertices + GetLength(vertices, 0) * GetLength(vertices, 1) * i); if (arrays[aiColors] != 0) glColorPointer (GetLength(arrays[aiColors], 0), GL_DOUBLE, 0, arrays[aiColors] + GetLength(arrays[aiColors], 0) * GetLength(arrays[aiColors], 1) * i); // if (arrays[aiEdgeFlags] != 0) // glEdgeFlagPointer(0, arrays[aiEdgeFlags]); glDrawArrays(glDrawModeMap[drawMode], 0, GetLength(vertices, 1)); } } if (vertices != 0) glDisableClientState(GL_VERTEX_ARRAY); if (arrays[aiColors ] != 0) glDisableClientState(GL_COLOR_ARRAY); if (arrays[aiEdgeFlags] != 0) glDisableClientState(GL_EDGE_FLAG_ARRAY); if (drawMode >= odmTriangles && drawMode <= odmPolygon) { if (arrays[aiPolygonStipple] != 0) glDisable(GL_POLYGON_STIPPLE); } if (drawMode >= odmLines && drawMode <= odmLineLoop) { if (lineStipple != 0) glDisable(GL_LINE_STIPPLE); if (lineWidth != 1.0) glLineWidth(1.0); } if (drawMode == odmPoints && pointSize != 1.0) glPointSize(1.0); glPopMatrix(); }
int main() { // INIT glfwSetErrorCallback( error_callback ); /* Initialize the library */ if ( !glfwInit() ) { return -1; } // must use exactly version 3 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 ); /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow( WIDTH, HEIGHT, "Hello World", NULL, NULL ); if ( !window ) { glfwTerminate(); return -1; } glfwMakeContextCurrent( window ); glfwSetKeyCallback( window, key_callback ); //glfwSetCursorPosCallback(window, cursor_position_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); int count; //printf( "%s\n", glfwGetVideoModes( glfwGetPrimaryMonitor(), &count ) ); glewExperimental = GL_TRUE; if( glewInit() != GLEW_OK ) { fprintf( stderr, "glewInit() failed\n" ); } glViewport( 0, 0, WIDTH, HEIGHT ); glClearColor( 0.2f, 0.3f, 0.3f, 1.0f ); glEnable( GL_DEPTH_TEST ); // SHADER Shader shader( "./primitive_restart.vs.glsl", "./primitive_restart.fs.glsl" ); static const GLfloat cube_positions[] = { -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f }; static const GLfloat cube_colors[] = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f }; static const GLushort cube_indices[] = { 0, 1, 2, 3, 6, 7, 4, 5, 0xFFFF, 2, 6, 0, 4, 1, 5, 3, 7 }; GLuint VBO; glGenBuffers( 1, &VBO ); glBindBuffer( GL_ARRAY_BUFFER, VBO ); glBufferData( GL_ARRAY_BUFFER, sizeof(cube_positions) + sizeof(cube_colors), NULL, GL_STATIC_DRAW ); glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(cube_positions), cube_positions); glBufferSubData( GL_ARRAY_BUFFER, sizeof(cube_positions), sizeof(cube_colors), cube_colors); GLuint EBO; glGenBuffers( 1, &EBO ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, EBO ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_indices), cube_indices, GL_STATIC_DRAW ); GLuint VAO; glGenVertexArrays( 1, &VAO ); glBindVertexArray( VAO ); glEnableVertexAttribArray( 0 ); glEnableVertexAttribArray( 1 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, NULL ); glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)sizeof(cube_positions) ); glClearColor( 0.6f, 0.8f, 0.8f, 1.0f ); glm::mat4 projection; projection = glm::perspective( 45.0f, (GLfloat)WIDTH/HEIGHT, 0.1f, 100.0f ); // Game loop while( !glfwWindowShouldClose( window ) ) { //for( int iter = 1; iter; --iter ) { glfwPollEvents(); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glUseProgram( shader.Program ); glm::mat4 models[2]; updateCamera(); //glm::mat4 rotatedView = camera[1] * camera[0] * view; printf( "rotation x %f, y %f, z %f\n", rotation.x, rotation.y, rotation.z ); glm::mat4 rotatedView; rotatedView = glm::rotate( rotatedView, rotation.x, glm::vec3(1, 0, 0) ) ; rotatedView = glm::rotate( rotatedView, rotation.y, glm::vec3(0, 1, 0) ) ; rotatedView = glm::rotate( rotatedView, rotation.z, glm::vec3(0, 0, 1) ) ; rotatedView *= view; //view = glm::translate( view, position ); //glm::mat4 rotatedView; //projection = glm::rotate( projection, glm::radians(cameraOrientation[1]), glm::vec3(1.0f, 0.0f, 0.0f) ); //projection = glm::rotate( projection, glm::radians(cameraOrientation[0]), glm::vec3(0.0f, 1.0f, 0.0f) ); //projection = projection * (cameraPosition / 10.0f); glUniformMatrix4fv( glGetUniformLocation(shader.Program, "view" ), 1, GL_FALSE, glm::value_ptr(rotatedView) ); glUniformMatrix4fv( glGetUniformLocation(shader.Program, "projection" ), 1, GL_FALSE, glm::value_ptr(projection) ); glBindVertexArray( VAO ); glBindBuffer( GL_ARRAY_BUFFER, VBO ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, EBO ); //glDrawArrays( GL_TRIANGLES, 0, 6 ); glEnable(GL_PRIMITIVE_RESTART); glPrimitiveRestartIndex(0xFFFF); glDrawElements(GL_TRIANGLE_STRIP, 17, GL_UNSIGNED_SHORT, NULL); //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, NULL); //glBindVertexArray( 0 ); glFlush(); glfwSwapBuffers( window ); fps(); printf("\n"); } glDeleteVertexArrays( 1, &VAO ); glDeleteBuffers( 1, &VBO ); glDeleteBuffers( 1, &EBO ); glfwDestroyWindow( window ); glfwTerminate(); return 0; }
//draw a frame void RenderFrame() { //For some reason, vertex attribute arrays only seem to work if we sandwich the Clear //With Enable/Disable vertex program (at least for the first frame) glEnable(GL_VERTEX_PROGRAM_NV); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_VERTEX_PROGRAM_NV); glLoadIdentity(); //reset modelview matrix gluLookAt( 10*worldViewDirection.x, 10*worldViewDirection.y, 10*worldViewDirection.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); glRotatef(angle, 0.0f, 1.0f, 0.0f); if(currentTechnique==SINGLE_PASS) { glPushAttrib(GL_ALL_ATTRIB_BITS); SetSinglePassStates(); //draw torus glDrawElements(GL_TRIANGLES, torus.numIndices, GL_UNSIGNED_INT, torus.indices); glPopAttrib(); } if(currentTechnique==TEXTURE_LOOKUP) { glPushAttrib(GL_ALL_ATTRIB_BITS); SetDiffuseDecalStates(); //draw torus glDrawElements(GL_TRIANGLES, torus.numIndices, GL_UNSIGNED_INT, torus.indices); glPopAttrib(); //add specular glPushAttrib(GL_ALL_ATTRIB_BITS); glBlendFunc(GL_ONE, GL_ONE); glEnable(GL_BLEND); SetLookUpSpecularStates(); //draw torus glDrawElements(GL_TRIANGLES, torus.numIndices, GL_UNSIGNED_INT, torus.indices); glPopAttrib(); } if(currentTechnique==FALLBACK) { glPushAttrib(GL_ALL_ATTRIB_BITS); SetDiffuseStates(); //draw torus glDrawElements(GL_TRIANGLES, torus.numIndices, GL_UNSIGNED_INT, torus.indices); glPopAttrib(); //modulate by decal glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(GL_BLEND); glBlendFunc(GL_DST_COLOR, GL_ZERO); SetDecalStates(); glDrawElements(GL_TRIANGLES, torus.numIndices, GL_UNSIGNED_INT, torus.indices); glPopAttrib(); //add specular glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); SetSimpleSpecularStates(); glDrawElements(GL_TRIANGLES, torus.numIndices, GL_UNSIGNED_INT, torus.indices); glPopAttrib(); } fpsCounter.Update(); //update frames per second counter glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // window.StartTextMode(); // window.Print(0, 28, "FPS: %.2f", fpsCounter.GetFps()); //print the fps // glColor4f(1.0f, 1.0f, 0.0f, 0.0f); // if(currentTechnique==SINGLE_PASS) // window.Print(0, 48, "Single Pass Method"); // if(currentTechnique==TEXTURE_LOOKUP) // window.Print(0, 48, "NV_texture_shader Method"); // if(currentTechnique==FALLBACK) // window.Print(0, 48, "Fallback 3-pass Method"); // window.EndTextMode(); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // if(window.isKeyPressed(VK_F1)) // { // window.SaveScreenshot(); // window.SetKeyReleased(VK_F1); // } // All done drawing. Let's show it. glutSwapBuffers(); //check for any opengl errors // window.CheckGLError(); }
//draw sprites to framebuffer void Batch2D::Flush(){ UnmapBuffers(); glDrawElements(GL_TRIANGLES, instanceCount * indexPerSprite, GL_UNSIGNED_SHORT, 0); instanceCount = 0; MapBuffers(); }
void VR_Canvas::RenderCanvas(Camera * OrthoCamera) { OrthoCamera; privTransform(); privRenderState(OrthoCamera); // this->getAssignedAvatar()->getLeftEye()->getDistort float DistK[4]; float TexRange[2]; float LensOff[2]; float TexScale=0; float Aspect=0; this->ModelView = this->LocalToWorld * OrthoCamera->getViewMatrix(); Vect lightColor( 2.5f, 2.5f, 2.5f, 1.0f); glClearColor(0.0f, 0.0f, 0.0f, 1.0f ); this->getAssignedAvatar()->getLeftEye()->getDistortionRenderData(DistK, TexRange,LensOff,TexScale, Aspect); GLuint attribute_v_coord_postproc = glGetAttribLocation(VRManager::getInstance().getShaderProgram(), "v_coord"); GLuint uniform_fbo_texture = glGetUniformLocation(VRManager::getInstance().getShaderProgram(), "fbo_texture"); GLuint uniform_offset = glGetUniformLocation(VRManager::getInstance().getShaderProgram(), "offset"); uniform_offset;attribute_v_coord_postproc;uniform_fbo_texture; glUseProgram( VRManager::getInstance().getShaderProgram()); GLfloat offset = 0; glUniform1f(uniform_offset, offset); glBindTexture(GL_TEXTURE_2D, this->LeftPane.TBO); glUniform1i(uniform_fbo_texture,0); glEnableVertexAttribArray(attribute_v_coord_postproc); glBindVertexArray(this->LeftPane.VAO); glDrawElements(GL_TRIANGLES, 3*2, GL_UNSIGNED_SHORT, 0); glBindVertexArray(0); glDisableVertexAttribArray(attribute_v_coord_postproc); glBindTexture(GL_TEXTURE_2D,0); glUseProgram(0); this->getAssignedAvatar()->getRightEye()->getDistortionRenderData(DistK, TexRange,LensOff,TexScale, Aspect); glUseProgram( VRManager::getInstance().getShaderProgram()); offset = 1; glUniform1f(uniform_offset, offset); glBindTexture(GL_TEXTURE_2D, this->RightPane.TBO); glUniform1i(uniform_fbo_texture,0); glEnableVertexAttribArray(attribute_v_coord_postproc); glBindVertexArray(this->RightPane.VAO); glDrawElements(GL_TRIANGLES, 3*2, GL_UNSIGNED_SHORT, 0); glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D,0); glDisableVertexAttribArray(attribute_v_coord_postproc); glUseProgram(0); }
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // If text or lines are blurry when integrating ImGui in your engine: // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) ImGuiIO& io = ImGui::GetIO(); int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); if (fb_width == 0 || fb_height == 0) return; draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Backup GL state GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture); GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src); GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst); GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); GLboolean last_enable_blend = glIsEnabled(GL_BLEND); GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); // Setup viewport, orthographic projection matrix glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); const float ortho_projection[4][4] = { { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, {-1.0f, 1.0f, 0.0f, 1.0f }, }; glUseProgram(g_ShaderHandle); glUniform1i(g_AttribLocationTex, 0); glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); glBindVertexArray(g_VaoHandle); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawIdx* idx_buffer_offset = 0; glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW); for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } // Restore modified GL state glUseProgram(last_program); glActiveTexture(last_active_texture); glBindTexture(GL_TEXTURE_2D, last_texture); glBindVertexArray(last_vertex_array); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); glBlendFunc(last_blend_src, last_blend_dst); if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); }
int main(int argc, char *argv[]) { enum STATE state = STATE_INIT; /* initialize graphics */ SDL_Init(SDL_INIT_EVERYTHING); /* prepare opengl core profile */ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_Window *main_window = SDL_CreateWindow("glDrawElements", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, W, H, SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(main_window); glewExperimental=GL_TRUE; glewInit(); printf("GL_VENDOR: %s\n", glGetString(GL_VENDOR)); printf("GL_RENDERER: %s\n", glGetString(GL_RENDERER)); printf("GL_VERSION: %s\n", glGetString(GL_VERSION)); printf("GL_SHADING_LANGUAGE_VERSION: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); /* prepare default framebuffer */ glClearColor(0,0,1,1); /* prepare shaders */ GLuint vs_shader = glCreateShader(GL_VERTEX_SHADER); compile_shader(vs_shader, "glsl/pass.vert"); GLuint fs_shader = glCreateShader(GL_FRAGMENT_SHADER); compile_shader(fs_shader, "glsl/pass.frag"); GLuint program = glCreateProgram(); glAttachShader(program, vs_shader); glAttachShader(program, fs_shader); glLinkProgram(program); GLint linkStatus = 0; glGetProgramiv(program, GL_LINK_STATUS, &linkStatus ); if ( linkStatus != GL_TRUE ) { GLint logLength; glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logLength ); GLchar *infoLog = calloc(logLength+1, sizeof(char)); glGetProgramInfoLog( program, logLength, NULL, infoLog ); fprintf(stderr, "Failed to link shader glProgram: %s\n", infoLog); free(infoLog); exit(EXIT_FAILURE); } glUseProgram(program); /* prepare geometry */ GLuint vao = 0; glGenVertexArrays(1, &vao); glBindVertexArray(vao); /* here, besides the vbo for the vertices, there is an array of indexes that will define which vertices compose each geometry face */ GLuint ibo = 0; glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexes), indexes, GL_STATIC_DRAW); GLuint vbo = 0; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(geometry), geometry, GL_STATIC_DRAW); GLuint v_pos = glGetAttribLocation(program, "v_pos"); glEnableVertexAttribArray(v_pos); glVertexAttribPointer(v_pos, 3, GL_FLOAT, GL_FALSE, 0, (void*)(0)); GLuint color = glGetUniformLocation(program, "color"); glUniform4f(color, 1.f, 0.f, 0.f, 1.f); glBindBuffer(GL_ARRAY_BUFFER, 0); /* event loop */ state = STATE_RUNNING; while(state == STATE_RUNNING) { /* process input */ SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: state = STATE_EXIT; break; } } /* draw */ glClear(GL_COLOR_BUFFER_BIT); /* instead of draw arrays, we use draw elements, and pass the index count for the faces */ glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void*)0); SDL_GL_SwapWindow(main_window); } /* destroy */ SDL_GL_DeleteContext(context); SDL_DestroyWindow(main_window); return 0; }
void draw() const { indices.bindElems(); glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, NULL); }
void ExampleTestSuite::plotTest() { AE::PluginManager *pluginManager = AE::PluginManager::initialize(); #ifdef AE_PLATFORM_WIN32 AE::OS::WindowManager *windowManager = static_cast<AE::OS::WindowManager *>(pluginManager->registerPlugin("windowManager", new AE::OS::WindowManagerWin())); #else AE::OS::WindowManager *windowManager = static_cast<AE::OS::WindowManager *>(pluginManager->registerPlugin("windowManager", new AE::OS::WindowManagerLinux())); #endif pluginManager->getRoot()->attach(windowManager); assert(windowManager); windowManager->install(AE::NO_OPTIONS); AE::OS::WindowDesc windowDesc; windowDesc.dimensions = AE::Math::Point2<AE::uint>(640, 480); windowDesc.position = AE::Math::Point2<AE::int32>(100, 100); AE::OS::Window *window = windowManager->createWindow("Plot Test", windowDesc); PlotTestListener myWindowListener; AE::OS::EventQueue *eventQueue = windowManager->getEventQueue(); eventQueue->registerWindowListener(&myWindowListener); AE::Graphics::Device::Manager *deviceManager; AE::Graphics::Device::Driver *deviceDriver; #ifdef AE_PLATFORM_WIN32 deviceManager = static_cast<AE::Graphics::Device::Manager *>(pluginManager->registerPlugin("deviceManagerGL15", new AE::Graphics::Device::ManagerGL15())); deviceManager->install(0); deviceDriver = deviceManager->acquireDeviceDriver(0, AE::Graphics::Device::DT_GL_15); #else deviceManager = static_cast<AE::Graphics::Device::Manager *>(pluginManager->registerPlugin("deviceManagerGL15", new AE::Graphics::Device::ManagerGL15())); deviceManager->install(0); deviceDriver = deviceManager->acquireDeviceDriver(0, AE::Graphics::Device::DT_OPENGL1_5); #endif AE::Graphics::Device::ContextDesc contextDesc; contextDesc.dimensions = window->getDimensions(); contextDesc.fullScreen = false; contextDesc.parentWindow = window; contextDesc.setColorFormat(AE::Graphics::CF_R8G8B8A8); AE::Graphics::Device::Context *deviceContext = deviceDriver->createDeviceContext(contextDesc); window->show(); AE::Graphics::Color red(255, 0, 0); AE::Graphics::Color green(0, 255, 0); AE::Graphics::Color blue(0, 0, 255); AE::Graphics::Color black(0, 0, 0); AE::Graphics::Color white(255, 255, 255); #define VERTICES 0 #define INDICES 1 #define NUM_BUFFERS 2 #define BUFFER_OFFSET(i) ((void*)(i)) GLuint buffers[NUM_BUFFERS]; /*GLfloat vertices[][3] = { { -1.0, -1.0, -1.0 }, { 1.0, -1.0, -1.0 }, { 1.0, 1.0, -1.0 }, { -1.0, 1.0, -1.0 }, { -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 vertices[][3] = { { 100.0, 100.0, 0.0 }, { 100.0, 200.0, 0.0 }, { 0.0, 200.0, 0.0 }, { 0.0, 100.0, 0.0} }; /*GLubyte indices[][4] = { { 0, 1, 2, 3 }, { 4, 7, 6, 5 }, { 0, 4, 5, 1 }, { 3, 2, 6, 7 }, { 0, 3, 7, 4 }, { 1, 5, 6, 2 } };*/ GLubyte indices[] = { 0, 1, 2, 2, 3, 0 }; GLfloat colors[] = { 1, 1, 1, 1, 1, 0, 1, 0, 0, }; glEnable(GL_TEXTURE_2D); glEnable(GL_COLOR_MATERIAL); glGenBuffers(NUM_BUFFERS, buffers); glBindBuffer(GL_ARRAY_BUFFER, buffers[VERTICES]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[INDICES]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); while(myWindowListener.isRunning()) { deviceContext->beginRendering(black); AE::Graphics::Device::FrameBuffer *frameBuffer = deviceContext->getFrameBuffer(); frameBuffer->lock(AE::Graphics::LT_DISCARD); //frameBuffer->clear(red); frameBuffer->plot(green.getRGBA(), AE::Math::Point2<AE::int32>(100, 100)); drawLine(frameBuffer, white, AE::Math::Point2<AE::int32>(50, 50), AE::Math::Point2<AE::int32>(100, 50)); drawLine(frameBuffer, red, AE::Math::Point2<AE::int32>(101, 51), AE::Math::Point2<AE::int32>(150, 100)); drawLine(frameBuffer, blue, AE::Math::Point2<AE::int32>(151, 101), AE::Math::Point2<AE::int32>(250, 50)); //glBegin(GL_POLYGON); // These vertices form a closed polygon //glColor3f(1.0f, 1.0f, 0.0f); // Yellow //glVertex2f(300.f, 100.f); //glVertex2f(300.f, 300.f); //glVertex2f(100, 100); //glEnd(); glBindBuffer(GL_ARRAY_BUFFER, buffers[VERTICES]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[INDICES]); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)); //glDrawElements(GL_QUADS, 1, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0)); //glDrawArrays(GL_TRIANGLES, 0, 3); glDrawElements(GL_TRIANGLES, sizeof(indices), GL_UNSIGNED_BYTE, 0); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //std::vector<AE::Math::Point2<AE::int32>> points; //points.push_back(AE::Math::Point2<AE::int32>(400, 200)); //points.push_back(AE::Math::Point2<AE::int32>(403, 200)); //points.push_back(AE::Math::Point2<AE::int32>(406, 203)); //points.push_back(AE::Math::Point2<AE::int32>(403, 206)); //points.push_back(AE::Math::Point2<AE::int32>(400, 206)); //points.push_back(AE::Math::Point2<AE::int32>(397, 203)); //drawPolygon(frameBuffer, white, points); //std::vector<AE::Math::Point2<AE::int32>> points2; ///*points2.push_back(AE::Math::Point2(2, 3)); //points2.push_back(AE::Math::Point2(7, 1)); //points2.push_back(AE::Math::Point2(13, 5)); //points2.push_back(AE::Math::Point2(13, 11)); //points2.push_back(AE::Math::Point2(7, 7)); //points2.push_back(AE::Math::Point2(2, 9));*/ ///*points2.push_back(AE::Math::Point2(50, 50)); //points2.push_back(AE::Math::Point2(30, 30)); //points2.push_back(AE::Math::Point2(70, 30));*/ //points2.push_back(AE::Math::Point2<AE::int32>(200, 200)); //points2.push_back(AE::Math::Point2<AE::int32>(300, 200)); //points2.push_back(AE::Math::Point2<AE::int32>(350, 275)); //points2.push_back(AE::Math::Point2<AE::int32>(300, 350)); //points2.push_back(AE::Math::Point2<AE::int32>(200, 350)); //points2.push_back(AE::Math::Point2<AE::int32>(150, 275)); //drawFilledPolygon(frameBuffer, white, points2); //drawCircle(frameBuffer, blue, AE::Math::Point2<AE::int32>(320, 240), AE::int32(5) ); //drawCircle(frameBuffer, red, AE::Math::Point2<AE::int32>(320, 240), AE::int32(10)); //drawCircle(frameBuffer, red, AE::Math::Point2<AE::int32>(320, 240), AE::int32(15)); //drawCircle(frameBuffer, red, AE::Math::Point2<AE::int32>(320, 240), AE::int32(20)); //drawCircle(frameBuffer, red, AE::Math::Point2<AE::int32>(320, 240), AE::int32(25)); //drawCircle(frameBuffer, red, AE::Math::Point2<AE::int32>(320, 240), AE::int32(30)); //drawCircle(frameBuffer, red, AE::Math::Point2<AE::int32>(320, 240), AE::int32(35)); //drawCircle(frameBuffer, red, AE::Math::Point2<AE::int32>(320, 240), AE::int32(40)); //drawCircle(frameBuffer, red, AE::Math::Point2<AE::int32>(320, 240), AE::int32(45)); //drawCircle(frameBuffer, blue, AE::Math::Point2<AE::int32>(320, 240), AE::int32(50)); frameBuffer->unlock(); deviceContext->endRendering(); eventQueue->getNextEvent(0); } pluginManager->shutdown(); }
enum piglit_result piglit_display(void) { GLboolean pass = GL_TRUE; GLuint q; float *ptr; unsigned i, qresult; static const float verts[] = { 10, 10, 10, 20, 20, 20, 20, 10 }; static const float expected[] = { -0.687500, -0.375000, 0.000000, 1.000000, -0.687500, 0.250000, 0.000000, 1.000000, -0.375000, -0.375000, 0.000000, 1.000000, -0.687500, 0.250000, 0.000000, 1.000000, -0.375000, 0.250000, 0.000000, 1.000000, -0.375000, -0.375000, 0.000000, 1.000000, }; static const unsigned indices[] = { 0, 1, 3, 1, 2, 3 }; static const float clearcolor[] = {0.2, 0.2, 0.2}; static const float white[] = {1, 1, 1}; static const float red[] = {1, 0, 0}; glClear(GL_COLOR_BUFFER_BIT); /* Set up queries. */ switch (test) { case PRIMGEN: glGenQueries(1, &q); glBeginQuery(GL_PRIMITIVES_GENERATED_EXT, q); break; case PRIMWRITTEN: glGenQueries(1, &q); glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT, q); break; } /* Render into TFBO. */ glLoadIdentity(); piglit_UseProgram(prog); if (discard) glEnable(GL_RASTERIZER_DISCARD_EXT); piglit_BeginTransformFeedback(GL_TRIANGLES); glBindBuffer(GL_ARRAY_BUFFER, 0); glVertexPointer(2, GL_FLOAT, 0, verts); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, indices); piglit_EndTransformFeedback(); if (discard) glDisable(GL_RASTERIZER_DISCARD_EXT); assert(glGetError() == 0); switch (test) { case READBACK: puts("Testing readback."); ptr = glMapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER_EXT, GL_READ_ONLY); for (i = 0; i < BUF_FLOATS; i++) { float value = i >= offset && i < offset+range ? expected[i-offset] : DEFAULT_VALUE; //printf("%f, ", ptr[i]); if (fabs(ptr[i] - value) > 0.01) { printf("Buffer[%i]: %f, Expected: %f\n", i, ptr[i], value); pass = GL_FALSE; } } glUnmapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER_EXT); break; case RENDER: puts("Testing rendering."); piglit_UseProgram(prog_passthrough); glBindBuffer(GL_ARRAY_BUFFER, buf); glVertexPointer(4, GL_FLOAT, 0, (void*)(intptr_t)(offset * sizeof(float))); glDrawArrays(GL_TRIANGLES, 0, range == MAX_RANGE ? 6 : 3); pass = piglit_probe_pixel_rgb(33, 18, range == MAX_RANGE ? red : clearcolor) && pass; pass = piglit_probe_pixel_rgb(28, 12, red) && pass; break; case PRIMGEN: puts("Testing a primitives-generated query."); glEndQuery(GL_PRIMITIVES_GENERATED_EXT); glGetQueryObjectuiv(q, GL_QUERY_RESULT, &qresult); { int expected = 2; /* RASTERIZER_DISCARD should not affect this. */ if (qresult != expected) { printf("Primitives generated: %i, Expected: %i\n", qresult, expected); pass = GL_FALSE; } } break; case PRIMWRITTEN: puts("Testing a primitives-written query."); glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT); glGetQueryObjectuiv(q, GL_QUERY_RESULT, &qresult); { int expected = range == MAX_RANGE ? 2 : 1; if (qresult != expected) { printf("Primitives written: %i, Expected: %i\n", qresult, expected); pass = GL_FALSE; } } break; default: piglit_report_result(PIGLIT_SKIP); } pass = piglit_probe_pixel_rgb(5, 5, clearcolor) && pass; pass = piglit_probe_pixel_rgb(15, 15, discard ? clearcolor : white) && pass; assert(glGetError() == 0); piglit_present_results(); return pass ? PIGLIT_PASS : PIGLIT_FAIL; }
void ThreeDimLife::draw() { // Rotate/translate the projection matrix glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glMatrixMode(GL_PROJECTION); glPushMatrix(); glTranslatef(0.0,0.0,-(zoomAmount+5)); glRotatef(rotateX, 1.0, 0.0, 0.0); glRotatef(rotateY, 0.0, 1.0, 0.0); glRotatef(rotateZ, 0.0, 0.0, 1.0); // Switch to modelview mode and draw the scene glMatrixMode(GL_MODELVIEW); glPushMatrix(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Setup the lights glLightfv(GL_LIGHT0, GL_POSITION, light_position[0]); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color[0]); glLightfv(GL_LIGHT0, GL_SPECULAR, light_color[0]); glLightfv(GL_LIGHT1, GL_POSITION, light_position[1]); glLightfv(GL_LIGHT1, GL_DIFFUSE, light_color[1]); glLightfv(GL_LIGHT1, GL_SPECULAR, light_color[1]); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient[0]); glLoadIdentity(); static GLfloat cubeCorners[] = {0.02f, 0.98f, 0.98f, 0.98f, 0.98f, 0.98f, 0.98f, 0.02f, 0.98f, 0.02f, 0.02f, 0.98f, 0.02f, 0.98f, 0.02f, 0.98f, 0.98f, 0.02f, 0.98f, 0.02f, 0.02f, 0.02f, 0.02f, 0.02f, }; static GLubyte indexes[] = {0, 1, 2, 3, 4, 5, 1, 0, 3, 2, 6, 7, 5, 4, 7, 6, 1, 5, 6, 2, 4, 0, 3, 7, }; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glEnable(GL_POLYGON_SMOOTH); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); // glTranslatef(-0.5*width, -0.5*height, 0); float dx = 100.0/width; float dy = 100.0/height; float dz = 100.0/depth; glEnableClientState(GL_VERTEX_ARRAY); glTranslatef(-0.5*width, -0.5*height, -0.5*depth); // qDebug() << "Drawing"; for (int i=0; i < height; ++i) { float cy = i*dy; for (int j=0; j<width; ++j) { float cx = j*dx; for (int k=0;k<depth; ++k) { float cz = k*dz; if (array[i][j][k]) { // Draw the box glPushMatrix(); // glScalef(0.25, 0.25, 0.25); glTranslatef(i, j, k); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse[BOX_MAT]); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient[BOX_MAT]); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular[BOX_MAT]); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess[BOX_MAT]); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glVertexPointer(3, GL_FLOAT, 0, cubeCorners); glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, indexes); glLineWidth(1.5); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse[LINE_MAT]); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient[LINE_MAT]); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular[LINE_MAT]); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess[LINE_MAT]); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);// Draw the outline glVertexPointer(3, GL_FLOAT, 0, cubeCorners); glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, indexes); glLineWidth(1.0); glPopMatrix(); } } } } // Reset to how we found things glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glFlush(); }
void GLIndexBuffer::Draw( GLenum mode ) { Bind(); glDrawElements(mode, size / sizeof(GLuint), GL_UNSIGNED_INT, NULL); Unbind(); }
void display() { // simulation if(runSimulation) { float *deviceVboPtr; int *deviceIboPtr; size_t num_bytes; cudaGraphicsMapResources(1, &cuVboResource, 0); cudaGraphicsMapResources(1, &cuIboResource, 0); cudaGraphicsResourceGetMappedPointer((void **)&deviceVboPtr, &num_bytes, cuVboResource); cudaGraphicsResourceGetMappedPointer((void **)&deviceIboPtr, &num_bytes, cuIboResource); launchParticleKernel(deviceVboPtr, deviceIboPtr, clothNumVertices, tTime, 0.1f, vertexSize, N, distance); cudaGraphicsUnmapResources(1, &cuVboResource, 0); cudaGraphicsUnmapResources(1, &cuIboResource, 0); } // mat4 viewM, projM, modelM; mat3 normalM; camera->getViewMatrix(viewM); camera->getProjMatrix(projM); modelM.setIdentity(); normalM = viewM.topLeftCorner<3,3>(); // TODO calc distance dependent point size vec3 eyeP; extractEyePosFromViewMatrix(viewM, eyeP); glPointSize(2.0f); // rendering glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw cloth volcanoShaderProgram->bind(); glUniformMatrix4fv(volcanoShaderProgram->uniform("view_matrix"), 1, false, viewM.data()); glUniformMatrix4fv(volcanoShaderProgram->uniform("proj_matrix"), 1, false, projM.data()); glUniformMatrix4fv(volcanoShaderProgram->uniform("model_matrix"), 1, false, modelM.data()); glUniformMatrix3fv(volcanoShaderProgram->uniform("normal_matrix"), 1, false, normalM.data()); glUniform1i(volcanoShaderProgram->uniform("bGlow"), 1); glBindBuffer(GL_ARRAY_BUFFER, clothVBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(0)); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(12)); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(24)); glEnableVertexAttribArray(2); glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(40)); glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, clothIBO); glDrawElements(GL_TRIANGLES, clothNumTriangleindices, GL_UNSIGNED_INT, (void*)(0)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); volcanoShaderProgram->release(); glutSwapBuffers(); }
void R_RemapDeluxeImages( world_t *world ) { int i; if( !tr.deluxemaps[0] ) return; R_InitConverter(); R_StateSetActiveTmuUntracked( GL_TEXTURE0 ); R_StateSetActiveClientTmuUntracked( GL_TEXTURE0 ); glPushAttrib( GL_ALL_ATTRIB_BITS ); glPushClientAttrib( GL_CLIENT_ALL_ATTRIB_BITS ); glEnableClientState( GL_VERTEX_ARRAY ); glEnableClientState( GL_NORMAL_ARRAY ); glEnableVertexAttribArrayARB( 6 ); glEnableVertexAttribArrayARB( 7 ); glClearColor( 0, 0, 0, 0 ); glDisable( GL_DEPTH_TEST ); glDisable( GL_STENCIL_TEST ); glDisable( GL_ALPHA_TEST ); glDisable( GL_BLEND ); glDisable( GL_CULL_FACE ); glDisable( GL_MULTISAMPLE ); glEnable( GL_POLYGON_SMOOTH ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glEnable( GL_VERTEX_PROGRAM_ARB ); glBindProgramARB( GL_VERTEX_PROGRAM_ARB, conv.vp ); glEnable( GL_FRAGMENT_PROGRAM_ARB ); glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, conv.fp ); glEnable( GL_TEXTURE_2D ); for( i = 0; i < tr.numLightmaps; i++ ) { int j, y; unsigned *buf0, *buf1; image_t *img = tr.deluxemaps[i]; glBindTexture( GL_TEXTURE_2D, img->texnum ); glClear( GL_COLOR_BUFFER_BIT ); glViewport( 0, img->uploadHeight, img->uploadWidth, img->uploadHeight ); glDisable( GL_VERTEX_PROGRAM_ARB ); glDisable( GL_FRAGMENT_PROGRAM_ARB ); glBegin( GL_QUADS ); { glTexCoord2f( 0, 0 ); glVertex2f( -1, -1 ); glTexCoord2f( 0, 1 ); glVertex2f( -1, 1 ); glTexCoord2f( 1, 1 ); glVertex2f( 1, 1 ); glTexCoord2f( 1, 0 ); glVertex2f( 1, -1 ); } glEnd(); glEnable( GL_VERTEX_PROGRAM_ARB ); glEnable( GL_FRAGMENT_PROGRAM_ARB ); glViewport( 0, 0, img->uploadWidth, img->uploadHeight ); glProgramLocalParameter4fARB( GL_VERTEX_PROGRAM_ARB, 0, img->uploadWidth, img->uploadHeight, 1.0F / img->uploadWidth, 1.0F / img->uploadHeight ); for( j = 0; j < world->numsurfaces; j++ ) { const msurface_t *srf = world->surfaces + j; const shader_t *shader = srf->shader; const msurface_ex_t *exsrf = srf->redirect; if( !shader->stages[0] || !shader->stages[0]->active ) continue; if( shader->stages[0]->deluxeMap != img ) continue; if( !exsrf ) continue; glVertexPointer( 2, GL_FLOAT, sizeof( drawVert_ex_t ), &exsrf->verts[0].uvL ); glNormalPointer( GL_FLOAT, sizeof( drawVert_ex_t ), &exsrf->verts[0].norm ); glVertexAttribPointerARB( 6, 3, GL_FLOAT, GL_FALSE, sizeof( drawVert_ex_t ), &exsrf->verts[0].tan ); glVertexAttribPointerARB( 7, 3, GL_FLOAT, GL_FALSE, sizeof( drawVert_ex_t ), &exsrf->verts[0].bin ); glDrawElements( exsrf->primType, exsrf->numIndices, GL_UNSIGNED_SHORT, exsrf->indices ); } glFinish(); buf0 = (unsigned*)ri.Hunk_AllocateTempMemory( img->uploadWidth * img->uploadHeight * 4 ); buf1 = (unsigned*)ri.Hunk_AllocateTempMemory( img->uploadWidth * img->uploadHeight * 4 ); //can't just copy to the texture since we //need the custom mipmap generator glReadPixels( 0, 0, img->uploadWidth, img->uploadHeight, GL_RGBA, GL_UNSIGNED_BYTE, buf0 ); #define DELUXEL( buf, x, y ) ((byte*)(buf) + (((y) * img->uploadWidth + (x)) * 4)) Com_Memcpy( buf1, buf0, img->uploadWidth * img->uploadHeight * 4 ); for( j = 0; j < 4; j++ ) { for( y = 0; y < img->uploadHeight; y++ ) { int x; for( x = 0; x < img->uploadWidth; x++ ) { static int neighbors[8][2] = { { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 } }; int i; int sum[3], c; byte *cIn = DELUXEL( buf0, x, y ); byte *cOut = DELUXEL( buf1, x, y ); cOut[3] = cIn[3]; if( cIn[2] ) { //if it has some Z value //then it's already good cOut[0] = cIn[0]; cOut[1] = cIn[1]; cOut[2] = cIn[2]; continue; } c = 0; sum[0] = sum[1] = sum[2] = 0; for( i = 0; i < lengthof( neighbors ); i++ ) { int nx = x + neighbors[i][0]; int ny = y + neighbors[i][1]; if( nx >= 0 && nx < img->uploadWidth && ny >= 0 && ny < img->uploadHeight ) { byte *n = DELUXEL( buf0, nx, ny ); if( !n[2] ) continue; sum[0] += n[0]; sum[1] += n[1]; sum[2] += n[2]; c++; } } if( c ) { cOut[0] = sum[0] / c; cOut[1] = sum[1] / c; cOut[2] = sum[2] / c; } } } Com_Memcpy( buf0, buf1, img->uploadWidth * img->uploadHeight * 4 ); } for( y = 0; y < img->uploadHeight; y++ ) { int x; for( x = 0; x < img->uploadWidth; x++ ) { byte *d = DELUXEL( buf1, x, y ); if( !d[2] ) { d[0] = 0; d[1] = 0; d[2] = 0xFF; } } } //write it out to file { int size; char path[MAX_QPATH]; byte *out_buf; Com_sprintf( path, sizeof( path ), "deluxe/%s/dm_%04d.tga", world->baseName, i ); size = 18 + img->uploadWidth * img->uploadHeight * 3; out_buf = (byte*)ri.Hunk_AllocateTempMemory( size ); Com_Memset( out_buf, 0, 18 ); out_buf[2] = 2; // uncompressed type out_buf[12] = img->uploadWidth & 255; out_buf[13] = img->uploadWidth >> 8; out_buf[14] = img->uploadHeight & 255; out_buf[15] = img->uploadHeight >> 8; out_buf[16] = 24; // pixel size out_buf[17] = 0x20; // reverse row order for( y = 0; y < img->uploadHeight; y++ ) { int x; for( x = 0; x < img->uploadWidth; x++ ) { byte *d = DELUXEL( buf1, x, y ); out_buf[18 + (y * img->uploadWidth + x) * 3 + 0] = d[2]; out_buf[18 + (y * img->uploadWidth + x) * 3 + 1] = d[1]; out_buf[18 + (y * img->uploadWidth + x) * 3 + 2] = d[0]; } } ri.FS_WriteFile( path, out_buf, size ); ri.Hunk_FreeTempMemory( out_buf ); } #undef DELUXEL Upload32( buf1, qfalse, img, ILF_VECTOR_SB3 ); #ifdef _DEBUG glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, img->texnum ); glViewport( img->uploadWidth, 0, img->uploadWidth, img->uploadHeight ); glDisable( GL_VERTEX_PROGRAM_ARB ); glDisable( GL_FRAGMENT_PROGRAM_ARB ); glBegin( GL_QUADS ); { glTexCoord2f( 0, 0 ); glVertex2f( -1, -1 ); glTexCoord2f( 0, 1 ); glVertex2f( -1, 1 ); glTexCoord2f( 1, 1 ); glVertex2f( 1, 1 ); glTexCoord2f( 1, 0 ); glVertex2f( 1, -1 ); } glEnd(); glEnable( GL_VERTEX_PROGRAM_ARB ); glEnable( GL_FRAGMENT_PROGRAM_ARB ); GLimp_EndFrame(); #endif ri.Hunk_FreeTempMemory( buf1 ); ri.Hunk_FreeTempMemory( buf0 ); } glPopClientAttrib(); glPopAttrib(); glDeleteProgramsARB( 1, &conv.vp ); glDeleteProgramsARB( 1, &conv.fp ); }
void BatchedSprite::set_buffer_data() { _num_indices = _count/2*3; // set texture glBindTexture(GL_TEXTURE_2D, _image_id); // create vbo if (_vbo == 0 && _ibo == 0) { glGenBuffers(1, &_vbo); glGenBuffers(1, &_ibo); } // vbo if (_previous_count == _count) { glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferSubData(GL_ARRAY_BUFFER, 0, (int)_data.size() * sizeof(TextureData2D), &_data[0]); } else { glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, (int)_data.size() * sizeof(TextureData2D), &_data[0], _usage); } // ibo if (_previous_count == _count) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo); } else { std::vector<GLuint> indices = std::vector<GLuint>(_num_indices); //GLuint indices[_num_indices]; for (int i=0; i<_num_indices/6; i++) { if (i==0) { indices[i] = i*4; indices[i+1] = i*4+1; indices[i+2] = i*4+2; indices[i+3] = i*4; indices[i+4] = i*4+2; indices[i+5] = i*4+3; } else { indices[i*6] = i*4; indices[i*6+1] = i*4+1; indices[i*6+2] = i*4+2; indices[i*6+3] = i*4; indices[i*6+4] = i*4+2; indices[i*6+5] = i*4+3; } } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _num_indices * sizeof(GLuint), &indices[0], _usage); } // set texture coord data if (_texture_program != NULL) { _texture_program->set_texture_coordinate_pointer(sizeof(TextureData2D), (GLvoid*)offsetof(TextureData2D, texture_coordinate)); _texture_program->set_vertex_pointer(sizeof(TextureData2D), (GLvoid*)offsetof(TextureData2D, position)); } else if (_font_program != NULL) { _font_program->set_texture_coordinate_pointer(sizeof(TextureData2D), (GLvoid*)offsetof(TextureData2D, texture_coordinate)); _font_program->set_vertex_pointer(sizeof(TextureData2D), (GLvoid*)offsetof(TextureData2D, position)); } // draw if (!_static) { glDrawElements(GL_TRIANGLES, _num_indices, GL_UNSIGNED_INT, NULL); } }