RenderState.cpp revision 818c9fbf1d76d5df19253ba4eb964efa939ec9ec
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16#include "renderstate/RenderState.h" 17 18#include "renderthread/CanvasContext.h" 19#include "renderthread/EglManager.h" 20#include "utils/GLUtils.h" 21 22#include <algorithm> 23 24namespace android { 25namespace uirenderer { 26 27RenderState::RenderState(renderthread::RenderThread& thread) 28 : mRenderThread(thread) 29 , mViewportWidth(0) 30 , mViewportHeight(0) 31 , mFramebuffer(0) { 32 mThreadId = pthread_self(); 33} 34 35RenderState::~RenderState() { 36 LOG_ALWAYS_FATAL_IF(mBlend || mMeshState || mScissor || mStencil, 37 "State object lifecycle not managed correctly"); 38} 39 40void RenderState::onGLContextCreated() { 41 LOG_ALWAYS_FATAL_IF(mBlend || mMeshState || mScissor || mStencil, 42 "State object lifecycle not managed correctly"); 43 mBlend = new Blend(); 44 mMeshState = new MeshState(); 45 mScissor = new Scissor(); 46 mStencil = new Stencil(); 47 48 // This is delayed because the first access of Caches makes GL calls 49 if (!mCaches) { 50 mCaches = &Caches::createInstance(*this); 51 } 52 mCaches->init(); 53 mCaches->textureCache.setAssetAtlas(&mAssetAtlas); 54} 55 56static void layerLostGlContext(Layer* layer) { 57 layer->onGlContextLost(); 58} 59 60void RenderState::onGLContextDestroyed() { 61/* 62 size_t size = mActiveLayers.size(); 63 if (CC_UNLIKELY(size != 0)) { 64 ALOGE("Crashing, have %d contexts and %d layers at context destruction. isempty %d", 65 mRegisteredContexts.size(), size, mActiveLayers.empty()); 66 mCaches->dumpMemoryUsage(); 67 for (std::set<renderthread::CanvasContext*>::iterator cit = mRegisteredContexts.begin(); 68 cit != mRegisteredContexts.end(); cit++) { 69 renderthread::CanvasContext* context = *cit; 70 ALOGE("Context: %p (root = %p)", context, context->mRootRenderNode.get()); 71 ALOGE(" Prefeteched layers: %zu", context->mPrefetechedLayers.size()); 72 for (std::set<RenderNode*>::iterator pit = context->mPrefetechedLayers.begin(); 73 pit != context->mPrefetechedLayers.end(); pit++) { 74 (*pit)->debugDumpLayers(" "); 75 } 76 context->mRootRenderNode->debugDumpLayers(" "); 77 } 78 79 80 if (mActiveLayers.begin() == mActiveLayers.end()) { 81 ALOGE("set has become empty. wat."); 82 } 83 for (std::set<const Layer*>::iterator lit = mActiveLayers.begin(); 84 lit != mActiveLayers.end(); lit++) { 85 const Layer* layer = *(lit); 86 ALOGE("Layer %p, state %d, texlayer %d, fbo %d, buildlayered %d", 87 layer, layer->state, layer->isTextureLayer(), layer->getFbo(), layer->wasBuildLayered); 88 } 89 LOG_ALWAYS_FATAL("%d layers have survived gl context destruction", size); 90 } 91*/ 92 93 // TODO: reset all cached state in state objects 94 std::for_each(mActiveLayers.begin(), mActiveLayers.end(), layerLostGlContext); 95 mAssetAtlas.terminate(); 96 97 mCaches->terminate(); 98 99 delete mBlend; 100 mBlend = nullptr; 101 delete mMeshState; 102 mMeshState = nullptr; 103 delete mScissor; 104 mScissor = nullptr; 105 delete mStencil; 106 mStencil = nullptr; 107} 108 109void RenderState::setViewport(GLsizei width, GLsizei height) { 110 mViewportWidth = width; 111 mViewportHeight = height; 112 glViewport(0, 0, mViewportWidth, mViewportHeight); 113} 114 115 116void RenderState::getViewport(GLsizei* outWidth, GLsizei* outHeight) { 117 *outWidth = mViewportWidth; 118 *outHeight = mViewportHeight; 119} 120 121void RenderState::bindFramebuffer(GLuint fbo) { 122 if (mFramebuffer != fbo) { 123 mFramebuffer = fbo; 124 glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer); 125 } 126} 127 128GLuint RenderState::genFramebuffer() { 129 GLuint ret; 130 glGenFramebuffers(1, &ret); 131 return ret; 132} 133 134void RenderState::deleteFramebuffer(GLuint fbo) { 135 if (mFramebuffer == fbo) { 136 // GL defines that deleting the currently bound FBO rebinds FBO 0. 137 // Reflect this in our cached value. 138 mFramebuffer = 0; 139 } 140 glDeleteFramebuffers(1, &fbo); 141} 142 143void RenderState::invokeFunctor(Functor* functor, DrawGlInfo::Mode mode, DrawGlInfo* info) { 144 if (mode == DrawGlInfo::kModeProcessNoContext) { 145 // If there's no context we don't need to interrupt as there's 146 // no gl state to save/restore 147 (*functor)(mode, info); 148 } else { 149 interruptForFunctorInvoke(); 150 (*functor)(mode, info); 151 resumeFromFunctorInvoke(); 152 } 153} 154 155void RenderState::interruptForFunctorInvoke() { 156 mCaches->setProgram(nullptr); 157 mCaches->textureState().resetActiveTexture(); 158 meshState().unbindMeshBuffer(); 159 meshState().unbindIndicesBuffer(); 160 meshState().resetVertexPointers(); 161 meshState().disableTexCoordsVertexArray(); 162 debugOverdraw(false, false); 163} 164 165void RenderState::resumeFromFunctorInvoke() { 166 glViewport(0, 0, mViewportWidth, mViewportHeight); 167 glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer); 168 debugOverdraw(false, false); 169 170 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 171 172 scissor().invalidate(); 173 blend().invalidate(); 174 175 mCaches->textureState().activateTexture(0); 176 mCaches->textureState().resetBoundTextures(); 177} 178 179void RenderState::debugOverdraw(bool enable, bool clear) { 180 if (Properties::debugOverdraw && mFramebuffer == 0) { 181 if (clear) { 182 scissor().setEnabled(false); 183 stencil().clear(); 184 } 185 if (enable) { 186 stencil().enableDebugWrite(); 187 } else { 188 stencil().disable(); 189 } 190 } 191} 192 193void RenderState::requireGLContext() { 194 assertOnGLThread(); 195 LOG_ALWAYS_FATAL_IF(!mRenderThread.eglManager().hasEglContext(), 196 "No GL context!"); 197} 198 199void RenderState::assertOnGLThread() { 200 pthread_t curr = pthread_self(); 201 LOG_ALWAYS_FATAL_IF(!pthread_equal(mThreadId, curr), "Wrong thread!"); 202} 203 204class DecStrongTask : public renderthread::RenderTask { 205public: 206 DecStrongTask(VirtualLightRefBase* object) : mObject(object) {} 207 208 virtual void run() override { 209 mObject->decStrong(nullptr); 210 mObject = nullptr; 211 delete this; 212 } 213 214private: 215 VirtualLightRefBase* mObject; 216}; 217 218void RenderState::postDecStrong(VirtualLightRefBase* object) { 219 mRenderThread.queue(new DecStrongTask(object)); 220} 221 222/////////////////////////////////////////////////////////////////////////////// 223// Render 224/////////////////////////////////////////////////////////////////////////////// 225 226void RenderState::render(const Glop& glop, const Matrix4& orthoMatrix) { 227 const Glop::Mesh& mesh = glop.mesh; 228 const Glop::Mesh::Vertices& vertices = mesh.vertices; 229 const Glop::Mesh::Indices& indices = mesh.indices; 230 const Glop::Fill& fill = glop.fill; 231 232 // --------------------------------------------- 233 // ---------- Program + uniform setup ---------- 234 // --------------------------------------------- 235 mCaches->setProgram(fill.program); 236 237 if (fill.colorEnabled) { 238 fill.program->setColor(fill.color); 239 } 240 241 fill.program->set(orthoMatrix, 242 glop.transform.modelView, 243 glop.transform.meshTransform(), 244 glop.transform.transformFlags & TransformFlags::OffsetByFudgeFactor); 245 246 // Color filter uniforms 247 if (fill.filterMode == ProgramDescription::ColorFilterMode::Blend) { 248 const FloatColor& color = fill.filter.color; 249 glUniform4f(mCaches->program().getUniform("colorBlend"), 250 color.r, color.g, color.b, color.a); 251 } else if (fill.filterMode == ProgramDescription::ColorFilterMode::Matrix) { 252 glUniformMatrix4fv(mCaches->program().getUniform("colorMatrix"), 1, GL_FALSE, 253 fill.filter.matrix.matrix); 254 glUniform4fv(mCaches->program().getUniform("colorMatrixVector"), 1, 255 fill.filter.matrix.vector); 256 } 257 258 // Round rect clipping uniforms 259 if (glop.roundRectClipState) { 260 // TODO: avoid query, and cache values (or RRCS ptr) in program 261 const RoundRectClipState* state = glop.roundRectClipState; 262 const Rect& innerRect = state->innerRect; 263 glUniform4f(fill.program->getUniform("roundRectInnerRectLTRB"), 264 innerRect.left, innerRect.top, 265 innerRect.right, innerRect.bottom); 266 glUniformMatrix4fv(fill.program->getUniform("roundRectInvTransform"), 267 1, GL_FALSE, &state->matrix.data[0]); 268 269 // add half pixel to round out integer rect space to cover pixel centers 270 float roundedOutRadius = state->radius + 0.5f; 271 glUniform1f(fill.program->getUniform("roundRectRadius"), 272 roundedOutRadius); 273 } 274 275 // -------------------------------- 276 // ---------- Mesh setup ---------- 277 // -------------------------------- 278 // vertices 279 const bool force = meshState().bindMeshBufferInternal(vertices.bufferObject) 280 || (vertices.position != nullptr); 281 meshState().bindPositionVertexPointer(force, vertices.position, vertices.stride); 282 283 // indices 284 meshState().bindIndicesBufferInternal(indices.bufferObject); 285 286 if (vertices.attribFlags & VertexAttribFlags::TextureCoord) { 287 const Glop::Fill::TextureData& texture = fill.texture; 288 // texture always takes slot 0, shader samplers increment from there 289 mCaches->textureState().activateTexture(0); 290 291 if (texture.clamp != GL_INVALID_ENUM) { 292 texture.texture->setWrap(texture.clamp, true, false, texture.target); 293 } 294 if (texture.filter != GL_INVALID_ENUM) { 295 texture.texture->setFilter(texture.filter, true, false, texture.target); 296 } 297 298 mCaches->textureState().bindTexture(texture.target, texture.texture->id); 299 meshState().enableTexCoordsVertexArray(); 300 meshState().bindTexCoordsVertexPointer(force, vertices.texCoord, vertices.stride); 301 302 if (texture.textureTransform) { 303 glUniformMatrix4fv(fill.program->getUniform("mainTextureTransform"), 1, 304 GL_FALSE, &texture.textureTransform->data[0]); 305 } 306 } else { 307 meshState().disableTexCoordsVertexArray(); 308 } 309 int colorLocation = -1; 310 if (vertices.attribFlags & VertexAttribFlags::Color) { 311 colorLocation = fill.program->getAttrib("colors"); 312 glEnableVertexAttribArray(colorLocation); 313 glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, vertices.stride, vertices.color); 314 } 315 int alphaLocation = -1; 316 if (vertices.attribFlags & VertexAttribFlags::Alpha) { 317 // NOTE: alpha vertex position is computed assuming no VBO 318 const void* alphaCoords = ((const GLbyte*) vertices.position) + kVertexAlphaOffset; 319 alphaLocation = fill.program->getAttrib("vtxAlpha"); 320 glEnableVertexAttribArray(alphaLocation); 321 glVertexAttribPointer(alphaLocation, 1, GL_FLOAT, GL_FALSE, vertices.stride, alphaCoords); 322 } 323 // Shader uniforms 324 SkiaShader::apply(*mCaches, fill.skiaShaderData); 325 326 // ------------------------------------ 327 // ---------- GL state setup ---------- 328 // ------------------------------------ 329 blend().setFactors(glop.blend.src, glop.blend.dst); 330 331 // ------------------------------------ 332 // ---------- Actual drawing ---------- 333 // ------------------------------------ 334 if (indices.bufferObject == meshState().getQuadListIBO()) { 335 // Since the indexed quad list is of limited length, we loop over 336 // the glDrawXXX method while updating the vertex pointer 337 GLsizei elementsCount = mesh.elementCount; 338 const GLbyte* vertexData = static_cast<const GLbyte*>(vertices.position); 339 while (elementsCount > 0) { 340 GLsizei drawCount = std::min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6); 341 342 // rebind pointers without forcing, since initial bind handled above 343 meshState().bindPositionVertexPointer(false, vertexData, vertices.stride); 344 if (vertices.attribFlags & VertexAttribFlags::TextureCoord) { 345 meshState().bindTexCoordsVertexPointer(false, 346 vertexData + kMeshTextureOffset, vertices.stride); 347 } 348 349 glDrawElements(mesh.primitiveMode, drawCount, GL_UNSIGNED_SHORT, nullptr); 350 elementsCount -= drawCount; 351 vertexData += (drawCount / 6) * 4 * vertices.stride; 352 } 353 } else if (indices.bufferObject || indices.indices) { 354 glDrawElements(mesh.primitiveMode, mesh.elementCount, GL_UNSIGNED_SHORT, indices.indices); 355 } else { 356 glDrawArrays(mesh.primitiveMode, 0, mesh.elementCount); 357 } 358 359 // ----------------------------------- 360 // ---------- Mesh teardown ---------- 361 // ----------------------------------- 362 if (vertices.attribFlags & VertexAttribFlags::Alpha) { 363 glDisableVertexAttribArray(alphaLocation); 364 } 365 if (vertices.attribFlags & VertexAttribFlags::Color) { 366 glDisableVertexAttribArray(colorLocation); 367 } 368} 369 370void RenderState::dump() { 371 blend().dump(); 372 meshState().dump(); 373 scissor().dump(); 374 stencil().dump(); 375} 376 377} /* namespace uirenderer */ 378} /* namespace android */ 379