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