void TextureSprite::addPolygon(const CCPointVector &points) { /// copy vertices positions and texture coordinates for (const CCPoint &p : points) { /// The vertices position in pixel mVertexPos.push_back(vertex3(p.x, p.y, .0f)); /// x y z /// The texture is loaded upside down by OpenGL. (1 - Y coord) will swap the texture Y coordinate. mTexCoords.push_back(tex2(p.x / mTexSize.width, 1 - (p.y / mTexSize.height))); } }
void GlobeView::drawLocalClient(){ if(!mEarth) return; ci::gl::ScopedFaceCulling cull(true, GL_BACK); ci::gl::ScopedTextureBind tex0(mTexDiffuse, 0); ci::gl::ScopedTextureBind tex1(mTexNormal, 1); ci::gl::ScopedTextureBind tex2(mTexMask, 2); mEarth->draw(); }
/// // @returns the vertex position from the texture coordinate /// ccTex2F CCProgressTimer::textureCoordFromAlphaPoint(CCPoint alpha) { ccTex2F ret = {0.0f, 0.0f}; if (!m_pSprite) { return ret; } ccV3F_C4B_T2F_Quad quad = m_pSprite->getQuad(); CCPoint min = ccp(quad.bl.texCoords.u,quad.bl.texCoords.v); CCPoint max = ccp(quad.tr.texCoords.u,quad.tr.texCoords.v); return tex2(min.x * (1.f - alpha.x) + max.x * alpha.x, min.y * (1.f - alpha.y) + max.y * alpha.y); }
void CCSquirmAnimNode::rebuildVertices() { if(m_vertices_dirty) { memset(&m_sQuad, 0, sizeof(m_sQuad)); int w = m_obContentSize.width; int h = m_obContentSize.height; int texture_w = m_pobTexture->getPixelsWide(); int texture_h = m_pobTexture->getPixelsHigh(); float max_u0 = (float)w / (float)texture_w / m_texture_horz_scale; float max_u1 = max_u0 / m_mask_horz_scale; ccColor4B clr = ccc4(m_color.r, m_color.g, m_color.b, m_opacity); m_sQuad.bl.vertices = vertex3(0.0f, 0.0f, 0.0f); m_sQuad.bl.colors = clr; m_sQuad.bl.texCoords = tex2(0.0f, 1.0f); m_sQuad.bl.texCoords1 = tex2(m_mask_left_edge, 1.0f); m_sQuad.br.vertices = vertex3(m_obContentSize.width, 0.0f, 0.0f); m_sQuad.br.colors = clr; m_sQuad.br.texCoords = tex2(max_u0, 1.0f); m_sQuad.br.texCoords1 = tex2(m_mask_left_edge + max_u1, 1.0f); m_sQuad.tl.vertices = vertex3(0.0f, m_obContentSize.height, 0.0f); m_sQuad.tl.colors = clr; m_sQuad.tl.texCoords = tex2(0.0f, 0.0f); m_sQuad.tl.texCoords1 = tex2(m_mask_left_edge, 0.0f); m_sQuad.tr.vertices = vertex3(m_obContentSize.width, m_obContentSize.height, 0.0f); m_sQuad.tr.colors = clr; m_sQuad.tr.texCoords = tex2(max_u0, 0.0f); m_sQuad.tr.texCoords1 = tex2(m_mask_left_edge + max_u1, 0.0f); m_vertices_dirty = false; } }
void CCMotionStreak::update(float delta) { if (!m_bStartingPositionInitialized) { return; } delta *= m_fFadeDelta; unsigned int newIdx, newIdx2, i, i2; unsigned int mov = 0; // Update current points for(i = 0; i<m_uNuPoints; i++) { m_pPointState[i]-=delta; if(m_pPointState[i] <= 0) mov++; else { newIdx = i-mov; if(mov>0) { // Move data m_pPointState[newIdx] = m_pPointState[i]; // Move point m_pPointVertexes[newIdx] = m_pPointVertexes[i]; // Move vertices i2 = i*2; newIdx2 = newIdx*2; m_pVertices[newIdx2] = m_pVertices[i2]; m_pVertices[newIdx2+1] = m_pVertices[i2+1]; // Move color i2 *= 4; newIdx2 *= 4; m_pColorPointer[newIdx2+0] = m_pColorPointer[i2+0]; m_pColorPointer[newIdx2+1] = m_pColorPointer[i2+1]; m_pColorPointer[newIdx2+2] = m_pColorPointer[i2+2]; m_pColorPointer[newIdx2+4] = m_pColorPointer[i2+4]; m_pColorPointer[newIdx2+5] = m_pColorPointer[i2+5]; m_pColorPointer[newIdx2+6] = m_pColorPointer[i2+6]; }else newIdx2 = newIdx*8; const GLubyte op = (GLubyte)(m_pPointState[newIdx] * 255.0f); m_pColorPointer[newIdx2+3] = op; m_pColorPointer[newIdx2+7] = op; } } m_uNuPoints-=mov; // Append new point bool appendNewPoint = true; if(m_uNuPoints >= m_uMaxPoints) { appendNewPoint = false; } else if(m_uNuPoints>0) { bool a1 = ccpDistanceSQ(m_pPointVertexes[m_uNuPoints-1], m_tPositionR) < m_fMinSeg; bool a2 = (m_uNuPoints == 1) ? false : (ccpDistanceSQ(m_pPointVertexes[m_uNuPoints-2], m_tPositionR) < (m_fMinSeg * 2.0f)); if(a1 || a2) { appendNewPoint = false; } } if(appendNewPoint) { m_pPointVertexes[m_uNuPoints] = m_tPositionR; m_pPointState[m_uNuPoints] = 1.0f; // Color assignment const unsigned int offset = m_uNuPoints*8; *((ccColor3B*)(m_pColorPointer + offset)) = _displayedColor; *((ccColor3B*)(m_pColorPointer + offset+4)) = _displayedColor; // Opacity m_pColorPointer[offset+3] = 255; m_pColorPointer[offset+7] = 255; // Generate polygon if(m_uNuPoints > 0 && m_bFastMode ) { if(m_uNuPoints > 1) { ccVertexLineToPolygon(m_pPointVertexes, m_fStroke, m_pVertices, m_uNuPoints, 1); } else { ccVertexLineToPolygon(m_pPointVertexes, m_fStroke, m_pVertices, 0, 2); } } m_uNuPoints ++; } if( ! m_bFastMode ) { ccVertexLineToPolygon(m_pPointVertexes, m_fStroke, m_pVertices, 0, m_uNuPoints); } // Updated Tex Coords only if they are different than previous step if( m_uNuPoints && m_uPreviousNuPoints != m_uNuPoints ) { float texDelta = 1.0f / m_uNuPoints; for( i=0; i < m_uNuPoints; i++ ) { m_pTexCoords[i*2] = tex2(0, texDelta*i); m_pTexCoords[i*2+1] = tex2(1, texDelta*i); } m_uPreviousNuPoints = m_uNuPoints; } }
void LanczosFilter::performPaint(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data) { if (effects->compositingType() == KWin::OpenGLCompositing && (data.xScale() < 0.9 || data.yScale() < 0.9) && KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects) { if (!m_inited) init(); const QRect screenRect = Workspace::self()->clientArea(ScreenArea, w->screen(), w->desktop()); // window geometry may not be bigger than screen geometry to fit into the FBO if (m_shader && w->width() <= screenRect.width() && w->height() <= screenRect.height()) { double left = 0; double top = 0; double right = w->width(); double bottom = w->height(); foreach (const WindowQuad & quad, data.quads) { // we need this loop to include the decoration padding left = qMin(left, quad.left()); top = qMin(top, quad.top()); right = qMax(right, quad.right()); bottom = qMax(bottom, quad.bottom()); } double width = right - left; double height = bottom - top; if (width > screenRect.width() || height > screenRect.height()) { // window with padding does not fit into the framebuffer // so cut of the shadow left = 0; top = 0; width = w->width(); height = w->height(); } int tx = data.xTranslation() + w->x() + left * data.xScale(); int ty = data.yTranslation() + w->y() + top * data.yScale(); int tw = width * data.xScale(); int th = height * data.yScale(); const QRect textureRect(tx, ty, tw, th); const bool hardwareClipping = !(QRegion(textureRect)-region).isEmpty(); int sw = width; int sh = height; GLTexture *cachedTexture = static_cast< GLTexture*>(w->data(LanczosCacheRole).value<void*>()); if (cachedTexture) { if (cachedTexture->width() == tw && cachedTexture->height() == th) { cachedTexture->bind(); if (hardwareClipping) { glEnable(GL_SCISSOR_TEST); } if (ShaderManager::instance()->isValid()) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); const qreal rgb = data.brightness() * data.opacity(); const qreal a = data.opacity(); GLShader *shader = ShaderManager::instance()->pushShader(ShaderManager::SimpleShader); shader->setUniform(GLShader::Offset, QVector2D(0, 0)); shader->setUniform(GLShader::ModulationConstant, QVector4D(rgb, rgb, rgb, a)); shader->setUniform(GLShader::Saturation, data.saturation()); shader->setUniform(GLShader::AlphaToOne, 0); cachedTexture->render(region, textureRect, hardwareClipping); ShaderManager::instance()->popShader(); glDisable(GL_BLEND); } else { prepareRenderStates(cachedTexture, data.opacity(), data.brightness(), data.saturation()); cachedTexture->render(region, textureRect, hardwareClipping); restoreRenderStates(cachedTexture, data.opacity(), data.brightness(), data.saturation()); } if (hardwareClipping) { glDisable(GL_SCISSOR_TEST); } cachedTexture->unbind(); m_timer.start(5000, this); return; } else { // offscreen texture not matching - delete delete cachedTexture; cachedTexture = 0; w->setData(LanczosCacheRole, QVariant()); } } WindowPaintData thumbData = data; thumbData.setXScale(1.0); thumbData.setYScale(1.0); thumbData.setXTranslation(-w->x() - left); thumbData.setYTranslation(-w->y() - top); thumbData.setBrightness(1.0); thumbData.setOpacity(1.0); thumbData.setSaturation(1.0); // Bind the offscreen FBO and draw the window on it unscaled updateOffscreenSurfaces(); GLRenderTarget::pushRenderTarget(m_offscreenTarget); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); w->sceneWindow()->performPaint(mask, infiniteRegion(), thumbData); // Create a scratch texture and copy the rendered window into it GLTexture tex(sw, sh); tex.setFilter(GL_LINEAR); tex.setWrapMode(GL_CLAMP_TO_EDGE); tex.bind(); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, m_offscreenTex->height() - sh, sw, sh); // Set up the shader for horizontal scaling float dx = sw / float(tw); int kernelSize; m_shader->createKernel(dx, &kernelSize); m_shader->createOffsets(kernelSize, sw, Qt::Horizontal); m_shader->bind(); m_shader->setUniforms(); // Draw the window back into the FBO, this time scaled horizontally glClear(GL_COLOR_BUFFER_BIT); QVector<float> verts; QVector<float> texCoords; verts.reserve(12); texCoords.reserve(12); texCoords << 1.0 << 0.0; verts << tw << 0.0; // Top right texCoords << 0.0 << 0.0; verts << 0.0 << 0.0; // Top left texCoords << 0.0 << 1.0; verts << 0.0 << sh; // Bottom left texCoords << 0.0 << 1.0; verts << 0.0 << sh; // Bottom left texCoords << 1.0 << 1.0; verts << tw << sh; // Bottom right texCoords << 1.0 << 0.0; verts << tw << 0.0; // Top right GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setData(6, 2, verts.constData(), texCoords.constData()); vbo->render(GL_TRIANGLES); // At this point we don't need the scratch texture anymore tex.unbind(); tex.discard(); // create scratch texture for second rendering pass GLTexture tex2(tw, sh); tex2.setFilter(GL_LINEAR); tex2.setWrapMode(GL_CLAMP_TO_EDGE); tex2.bind(); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, m_offscreenTex->height() - sh, tw, sh); // Set up the shader for vertical scaling float dy = sh / float(th); m_shader->createKernel(dy, &kernelSize); m_shader->createOffsets(kernelSize, m_offscreenTex->height(), Qt::Vertical); m_shader->setUniforms(); // Now draw the horizontally scaled window in the FBO at the right // coordinates on the screen, while scaling it vertically and blending it. glClear(GL_COLOR_BUFFER_BIT); verts.clear(); verts << tw << 0.0; // Top right verts << 0.0 << 0.0; // Top left verts << 0.0 << th; // Bottom left verts << 0.0 << th; // Bottom left verts << tw << th; // Bottom right verts << tw << 0.0; // Top right vbo->setData(6, 2, verts.constData(), texCoords.constData()); vbo->render(GL_TRIANGLES); tex2.unbind(); tex2.discard(); m_shader->unbind(); // create cache texture GLTexture *cache = new GLTexture(tw, th); cache->setFilter(GL_LINEAR); cache->setWrapMode(GL_CLAMP_TO_EDGE); cache->bind(); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, m_offscreenTex->height() - th, tw, th); GLRenderTarget::popRenderTarget(); if (hardwareClipping) { glEnable(GL_SCISSOR_TEST); } if (ShaderManager::instance()->isValid()) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); const qreal rgb = data.brightness() * data.opacity(); const qreal a = data.opacity(); GLShader *shader = ShaderManager::instance()->pushShader(ShaderManager::SimpleShader); shader->setUniform(GLShader::Offset, QVector2D(0, 0)); shader->setUniform(GLShader::ModulationConstant, QVector4D(rgb, rgb, rgb, a)); shader->setUniform(GLShader::Saturation, data.saturation()); shader->setUniform(GLShader::AlphaToOne, 0); cache->render(region, textureRect, hardwareClipping); ShaderManager::instance()->popShader(); glDisable(GL_BLEND); } else { prepareRenderStates(cache, data.opacity(), data.brightness(), data.saturation()); cache->render(region, textureRect, hardwareClipping); restoreRenderStates(cache, data.opacity(), data.brightness(), data.saturation()); } if (hardwareClipping) { glDisable(GL_SCISSOR_TEST); } cache->unbind(); w->setData(LanczosCacheRole, QVariant::fromValue(static_cast<void*>(cache))); // Delete the offscreen surface after 5 seconds m_timer.start(5000, this); return; } } // if ( effects->compositingType() == KWin::OpenGLCompositing )
int main(int argc, const char * argv[]) { CommonSettings Settings; GLFWwindow *window = Settings.CreateWindow("EX_GS_T_1"); if (window == nullptr) { std::cout << "Create window failed" << std::endl; glfwTerminate(); return -1; } glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); cam.setFPS(GL_TRUE); GLfloat vertices[] = { 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 1.0f, }; GLuint VAO, VBO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); #ifdef __APPLE__ string path = "/Camera/1/"; #else string path = "\\Camera\\1\\"; #endif ShaderReader shader(Settings.CCExercisesPath(path + "EX_GS_C_1_Vertex.shader").c_str(), Settings.CCExercisesPath(path + "EX_GS_C_1_Fragment.shader").c_str()); GLuint textures[2]; TextureReader tex1(Settings.CCResourcesPath("container.jpg").c_str()); textures[0] = tex1.getTexture(); TextureReader tex2(Settings.CCResourcesPath("awesomeface.png").c_str()); textures[1] = tex2.getTexture(); glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; glm::mat4 modelMat; glm::mat4 viewMat; glm::mat4 projMat; GLint width, height; glfwGetFramebufferSize(window, &width, &height); shader.Use(); GLint modelLoc = glGetUniformLocation(shader.GetProgram(), "modelMat"); GLint viewLoc = glGetUniformLocation(shader.GetProgram(), "viewMat"); GLint projLoc = glGetUniformLocation(shader.GetProgram(), "projMat"); glEnable(GL_DEPTH_TEST); const GLchar* names[] = { "tex1", "tex2", }; GLint texLocs[2]; for (int i = 0; i < 2; i++) { texLocs[i] = glGetUniformLocation(shader.GetProgram(), names[i]); } while (!glfwWindowShouldClose(window)) { glfwPollEvents(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GLfloat currentTime = glfwGetTime(); deltaTime = currentTime - lastTime; lastTime = currentTime; do_movement(); shader.Use(); for (int i = 0; i < 2; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, textures[i]); glUniform1i(texLocs[i], i); } glBindVertexArray(VAO); viewMat = cam.getViewMatrix(); projMat = glm::perspective(cam.getZoom(), (GLfloat)width / height, 0.1f, 100.0f); for (int i = 0; i < 10; i++) { modelMat = glm::mat4(); modelMat = glm::translate(modelMat, cubePositions[i]); modelMat = glm::rotate(modelMat, glm::radians(currentTime * -90.0f), glm::vec3(0.5f, 1.0f, -0.5f)); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(modelMat)); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(viewMat)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projMat)); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindTexture(GL_TEXTURE_2D, 0); glBindVertexArray(0); glfwSwapBuffers(window); } return 0; }
ccTex2F CC3MeshNode::getVertexTexCoord2FForTextureUnit( GLuint texUnit, GLuint index ) { return _mesh ? _mesh->getVertexTexCoord2FForTextureUnit(texUnit, index) : tex2( 0.0f, 0.0f ); }
int main(int argc, const char * argv[]) { CommonSettings Settings; GLFWwindow *window = Settings.CreateWindow("EX_GS_T_1"); if (window == nullptr) { std::cout << "Create window failed" << std::endl; glfwTerminate(); return -1; } GLfloat vertices[] = { 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, }; GLuint indices[] = { 0, 1, 2, 0, 2, 3, }; GLuint VAO, VBO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); #ifdef __APPLE__ string path = "/Transformations/2/"; #else string path = "\\Transformations\\2\\"; #endif ShaderReader shader(Settings.CCExercisesPath(path + "EX_GS_T_2_Vertex.shader").c_str(), Settings.CCExercisesPath(path + "EX_GS_T_2_Fragment.shader").c_str()); GLuint textures[2]; TextureReader tex1(Settings.CCResourcesPath("container.jpg").c_str()); textures[0] = tex1.getTexture(); TextureReader tex2(Settings.CCResourcesPath("awesomeface.png").c_str()); textures[1] = tex2.getTexture(); const GLchar* names[] = { "tex1", "tex2", }; while (!glfwWindowShouldClose(window)) { glfwPollEvents(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); for (int i = 0; i < 2; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, textures[i]); glUniform1i(glGetUniformLocation(shader.GetProgram(), names[i]), i); } shader.Use(); glm::mat4 trans; trans = glm::translate(trans, glm::vec3(-0.5f, 0.5f, 0.0f)); trans = glm::scale(trans, glm::vec3(sin(glfwGetTime()), sin(glfwGetTime()), 1.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.GetProgram(), "transform"), 1, GL_FALSE, glm::value_ptr(trans)); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); trans = glm::mat4(); trans = glm::translate(trans, glm::vec3(0.5f, -0.5f, 0.0f)); trans = glm::rotate(trans, glm::radians((float)glfwGetTime() * 90.0f), glm::vec3(0.0f, 0.0f, 1.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.GetProgram(), "transform"), 1, GL_FALSE, glm::value_ptr(trans)); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindTexture(GL_TEXTURE_2D, 0); glBindVertexArray(0); glfwSwapBuffers(window); } return 0; }
NS_CC_BEGIN void ccVertexLineToPolygon(CCPoint *points, float stroke, ccVertex2F *vertices, ccTex2F *texCoords, unsigned int offset, unsigned int nuPoints) { nuPoints += offset; if(nuPoints<=1) return; stroke *= 0.5f; unsigned int idx; unsigned int nuPointsMinus = nuPoints-1; float texDelta = 1.0f/(float)nuPointsMinus; for(unsigned int i = offset; i<nuPoints; i++) { idx = i*2; CCPoint p1 = points[i]; CCPoint perpVector; if(i == 0) perpVector = ccpPerp(ccpNormalize(ccpSub(p1, points[i+1]))); else if(i == nuPointsMinus) perpVector = ccpPerp(ccpNormalize(ccpSub(points[i-1], p1))); else { CCPoint p2 = points[i+1]; CCPoint p0 = points[i-1]; CCPoint p2p1 = ccpNormalize(ccpSub(p2, p1)); CCPoint p0p1 = ccpNormalize(ccpSub(p0, p1)); // Calculate angle between vectors float angle = acosf(ccpDot(p2p1, p0p1)); if(angle < CC_DEGREES_TO_RADIANS(70)) perpVector = ccpPerp(ccpNormalize(ccpMidpoint(p2p1, p0p1))); else if(angle < CC_DEGREES_TO_RADIANS(170)) perpVector = ccpNormalize(ccpMidpoint(p2p1, p0p1)); else perpVector = ccpPerp(ccpNormalize(ccpSub(p2, p0))); } perpVector = ccpMult(perpVector, stroke); vertices[idx] = vertex2(p1.x+perpVector.x, p1.y+perpVector.y); vertices[idx+1] = vertex2(p1.x-perpVector.x, p1.y-perpVector.y); texCoords[idx] = tex2(0, texDelta*(float)i); texCoords[idx+1] = tex2(1, texDelta*(float)i); } // Validate vertexes offset = (offset==0) ? 0 : offset-1; for(unsigned int i = offset; i<nuPointsMinus; i++) { idx = i*2; const unsigned int idx1 = idx+2; ccVertex2F p1 = vertices[idx]; ccVertex2F p2 = vertices[idx+1]; ccVertex2F p3 = vertices[idx1]; ccVertex2F p4 = vertices[idx1+1]; float s; //BOOL fixVertex = !ccpLineIntersect(ccp(p1.x, p1.y), ccp(p4.x, p4.y), ccp(p2.x, p2.y), ccp(p3.x, p3.y), &s, &t); bool fixVertex = !ccVertexLineIntersect(p1.x, p1.y, p4.x, p4.y, p2.x, p2.y, p3.x, p3.y, &s); if(!fixVertex) if (s<0.0f || s>1.0f) fixVertex = true; if(fixVertex) { vertices[idx1] = p4; vertices[idx1+1] = p3; } } }
bool corpus_tester::test(const char* pCmd_line) { console::printf("Command line:\n\"%s\"", pCmd_line); static const command_line_params::param_desc param_desc_array[] = { { "corpus_test", 0, false }, { "in", 1, true }, { "deep", 0, false }, { "alpha", 0, false }, { "nomips", 0, false }, { "perceptual", 0, false }, { "endpointcaching", 0, false }, { "multithreaded", 0, false }, { "writehybrid", 0, false }, { "nobadblocks", 0, false }, }; command_line_params cmd_line_params; if (!cmd_line_params.parse(pCmd_line, CRNLIB_ARRAY_SIZE(param_desc_array), param_desc_array, true)) return false; double total_time1 = 0, total_time2 = 0; command_line_params::param_map_const_iterator it = cmd_line_params.begin(); for ( ; it != cmd_line_params.end(); ++it) { if (it->first != "in") continue; if (it->second.m_values.empty()) { console::error("Must follow /in parameter with a filename!\n"); return false; } for (uint in_value_index = 0; in_value_index < it->second.m_values.size(); in_value_index++) { const dynamic_string& filespec = it->second.m_values[in_value_index]; find_files file_finder; if (!file_finder.find(filespec.get_ptr(), find_files::cFlagAllowFiles | (cmd_line_params.has_key("deep") ? find_files::cFlagRecursive : 0))) { console::warning("Failed finding files: %s", filespec.get_ptr()); continue; } if (file_finder.get_files().empty()) { console::warning("No files found: %s", filespec.get_ptr()); return false; } const find_files::file_desc_vec& files = file_finder.get_files(); image_u8 o(4, 4), a(4, 4), b(4, 4); uint first_channel = 0; uint num_channels = 3; bool perceptual = cmd_line_params.get_value_as_bool("perceptual", false); if (perceptual) { first_channel = 0; num_channels = 0; } console::printf("Perceptual mode: %u", perceptual); for (uint file_index = 0; file_index < files.size(); file_index++) { const find_files::file_desc& file_desc = files[file_index]; console::printf("-------- Loading image: %s", file_desc.m_fullname.get_ptr()); image_u8 img; if (!image_utils::read_from_file(img, file_desc.m_fullname.get_ptr(), 0)) { console::warning("Failed loading image file: %s", file_desc.m_fullname.get_ptr()); continue; } if ((!cmd_line_params.has_key("alpha")) && img.is_component_valid(3)) { for (uint y = 0; y < img.get_height(); y++) for (uint x = 0; x < img.get_width(); x++) img(x, y).a = 255; img.set_component_valid(3, false); } mipmapped_texture orig_tex; orig_tex.assign(crnlib_new<image_u8>(img)); if (!cmd_line_params.has_key("nomips")) { mipmapped_texture::generate_mipmap_params genmip_params; genmip_params.m_srgb = true; console::printf("Generating mipmaps"); if (!orig_tex.generate_mipmaps(genmip_params, false)) { console::error("Mipmap generation failed!"); return false; } } console::printf("Compress 1"); mipmapped_texture tex1(orig_tex); dxt_image::pack_params convert_params; convert_params.m_endpoint_caching = cmd_line_params.get_value_as_bool("endpointcaching", 0, false); convert_params.m_compressor = cCRNDXTCompressorCRN; convert_params.m_quality = cCRNDXTQualityNormal; convert_params.m_perceptual = perceptual; convert_params.m_num_helper_threads = cmd_line_params.get_value_as_bool("multithreaded", 0, true) ? (g_number_of_processors - 1) : 0; convert_params.m_pProgress_callback = progress_callback; timer t; t.start(); if (!tex1.convert(PIXEL_FMT_ETC1, false, convert_params)) { console::error("Texture conversion failed!"); return false; } double time1 = t.get_elapsed_secs(); total_time1 += time1; console::printf("Elapsed time: %3.3f", time1); console::printf("Compress 2"); mipmapped_texture tex2(orig_tex); convert_params.m_endpoint_caching = false; convert_params.m_compressor = cCRNDXTCompressorCRN; convert_params.m_quality = cCRNDXTQualitySuperFast; t.start(); if (!tex2.convert(PIXEL_FMT_ETC1, false, convert_params)) { console::error("Texture conversion failed!"); return false; } double time2 = t.get_elapsed_secs(); total_time2 += time2; console::printf("Elapsed time: %3.3f", time2); image_u8 hybrid_img(img.get_width(), img.get_height()); for (uint l = 0; l < orig_tex.get_num_levels(); l++) { image_u8 orig_img, img1, img2; image_u8* pOrig = orig_tex.get_level(0, l)->get_unpacked_image(orig_img, cUnpackFlagUncook | cUnpackFlagUnflip); image_u8* pImg1 = tex1.get_level(0, l)->get_unpacked_image(img1, cUnpackFlagUncook | cUnpackFlagUnflip); image_u8* pImg2 = tex2.get_level(0, l)->get_unpacked_image(img2, cUnpackFlagUncook | cUnpackFlagUnflip); const uint num_blocks_x = pOrig->get_block_width(4); const uint num_blocks_y = pOrig->get_block_height(4); crnlib::vector<image_utils::error_metrics> metrics[2]; for (uint by = 0; by < num_blocks_y; by++) { for (uint bx = 0; bx < num_blocks_x; bx++) { pOrig->extract_block(o.get_ptr(), bx * 4, by * 4, 4, 4); pImg1->extract_block(a.get_ptr(), bx * 4, by * 4, 4, 4); pImg2->extract_block(b.get_ptr(), bx * 4, by * 4, 4, 4); image_utils::error_metrics em1; em1.compute(o, a, first_channel, num_channels); image_utils::error_metrics em2; em2.compute(o, b, first_channel, num_channels); metrics[0].push_back(em1); metrics[1].push_back(em2); if (em1.mPeakSNR < em2.mPeakSNR) { add_bad_block(o); hybrid_img.blit(bx * 4, by * 4, b); } else { hybrid_img.blit(bx * 4, by * 4, a); } } } if (cmd_line_params.has_key("writehybrid")) image_utils::write_to_file("hybrid.tga", hybrid_img, image_utils::cWriteFlagIgnoreAlpha); console::printf("---- Mip level: %u, Total blocks: %ux%u, %u", l, num_blocks_x, num_blocks_y, num_blocks_x * num_blocks_y); console::printf("Compressor 1:"); print_metric_stats(metrics[0], num_blocks_x, num_blocks_y); console::printf("Compressor 2:"); print_metric_stats(metrics[1], num_blocks_x, num_blocks_y); console::printf("Compressor 1 vs. 2:"); print_comparative_metric_stats(cmd_line_params, metrics[0], metrics[1], num_blocks_x, num_blocks_y); image_utils::error_metrics em; em.compute(*pOrig, *pImg1, 0, perceptual ? 0 : 3); em.print("Compressor 1: "); em.compute(*pOrig, *pImg2, 0, perceptual ? 0 : 3); em.print("Compressor 2: "); em.compute(*pOrig, hybrid_img, 0, perceptual ? 0 : 3); em.print("Best of Both: "); } } } // file_index } flush_bad_blocks(); console::printf("Total times: %4.3f vs. %4.3f", total_time1, total_time2); return true; }
C3DOTextureHandler::C3DOTextureHandler() { std::vector<TexFile*> texfiles = LoadTexFiles(); // TODO: make this use TextureAtlas directly CTextureAtlas atlas; atlas.SetName("3DOModelTextureAtlas"); IAtlasAllocator* atlasAlloc = atlas.GetAllocator(); // NOTE: most Intels report maxTextureSize=2048, some even 1024 (!) atlasAlloc->SetNonPowerOfTwo(globalRendering->supportNPOTs); atlasAlloc->SetMaxSize(std::min(globalRendering->maxTextureSize, 2048), std::min(globalRendering->maxTextureSize, 2048)); // default for 3DO primitives that point to non-existing textures textures["___dummy___"] = UnitTexture(0.0f, 0.0f, 1.0f, 1.0f); for (std::vector<TexFile*>::iterator it = texfiles.begin(); it != texfiles.end(); ++it) { atlasAlloc->AddEntry((*it)->name, int2((*it)->tex.xsize, (*it)->tex.ysize)); } const bool allocated = atlasAlloc->Allocate(); const int2 curAtlasSize = atlasAlloc->GetAtlasSize(); const int2 maxAtlasSize = atlasAlloc->GetMaxSize(); if (!allocated) { // either the algorithm simply failed to fit all // textures or the textures would really not fit LOG_L(L_WARNING, "[%s] failed to allocate 3DO texture-atlas memory (size=%dx%d max=%dx%d)", __FUNCTION__, curAtlasSize.x, curAtlasSize.y, maxAtlasSize.x, maxAtlasSize.y ); return; } else { assert(curAtlasSize.x <= maxAtlasSize.x); assert(curAtlasSize.y <= maxAtlasSize.y); } unsigned char* bigtex1 = new unsigned char[curAtlasSize.x * curAtlasSize.y * 4]; unsigned char* bigtex2 = new unsigned char[curAtlasSize.x * curAtlasSize.y * 4]; for (int a = 0; a < (curAtlasSize.x * curAtlasSize.y); ++a) { bigtex1[a*4 + 0] = 128; bigtex1[a*4 + 1] = 128; bigtex1[a*4 + 2] = 128; bigtex1[a*4 + 3] = 0; bigtex2[a*4 + 0] = 0; bigtex2[a*4 + 1] = 128; bigtex2[a*4 + 2] = 0; bigtex2[a*4 + 3] = 255; } for (std::vector<TexFile*>::iterator it = texfiles.begin(); it != texfiles.end(); ++it) { CBitmap& curtex1 = (*it)->tex; CBitmap& curtex2 = (*it)->tex2; const size_t foundx = atlasAlloc->GetEntry((*it)->name).x; const size_t foundy = atlasAlloc->GetEntry((*it)->name).y; const float4 texCoords = atlasAlloc->GetTexCoords((*it)->name); for (int y = 0; y < curtex1.ysize; ++y) { for (int x = 0; x < curtex1.xsize; ++x) { for (int col = 0; col < 4; ++col) { bigtex1[(((foundy + y) * curAtlasSize.x + (foundx + x)) * 4) + col] = curtex1.mem[(((y * curtex1.xsize) + x) * 4) + col]; bigtex2[(((foundy + y) * curAtlasSize.x + (foundx + x)) * 4) + col] = curtex2.mem[(((y * curtex1.xsize) + x) * 4) + col]; } } } textures[(*it)->name] = UnitTexture(texCoords); delete (*it); } const int maxMipMaps = atlasAlloc->GetMaxMipMaps(); { glGenTextures(1, &atlas3do1); glBindTexture(GL_TEXTURE_2D, atlas3do1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (maxMipMaps > 0) ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, maxMipMaps); if (maxMipMaps > 0) { glBuildMipmaps(GL_TEXTURE_2D, GL_RGBA8, curAtlasSize.x, curAtlasSize.y, GL_RGBA, GL_UNSIGNED_BYTE, bigtex1); //FIXME disable texcompression } else { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, curAtlasSize.x, curAtlasSize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, bigtex1); } } { glGenTextures(1, &atlas3do2); glBindTexture(GL_TEXTURE_2D, atlas3do2); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (maxMipMaps > 0) ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, maxMipMaps); if (maxMipMaps > 0) { glBuildMipmaps(GL_TEXTURE_2D, GL_RGBA8, curAtlasSize.x, curAtlasSize.y, GL_RGBA, GL_UNSIGNED_BYTE, bigtex2); //FIXME disable texcompression } else { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, curAtlasSize.x, curAtlasSize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, bigtex2); } } if (CTextureAtlas::GetDebug()) { CBitmap tex1(bigtex1, curAtlasSize.x, curAtlasSize.y); CBitmap tex2(bigtex2, curAtlasSize.x, curAtlasSize.y); tex1.Save(atlas.GetName() + "-1-" + IntToString(curAtlasSize.x) + "x" + IntToString(curAtlasSize.y) + ".png"); tex2.Save(atlas.GetName() + "-2-" + IntToString(curAtlasSize.x) + "x" + IntToString(curAtlasSize.y) + ".png"); } delete[] bigtex1; delete[] bigtex2; }