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