RenderState.cpp revision 031888744e24b5c7243ac99ec98b78aff5db1c78
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
21namespace android {
22namespace uirenderer {
23
24RenderState::RenderState(renderthread::RenderThread& thread)
25        : mRenderThread(thread)
26        , mViewportWidth(0)
27        , mViewportHeight(0)
28        , mFramebuffer(0) {
29    mThreadId = pthread_self();
30}
31
32RenderState::~RenderState() {
33    LOG_ALWAYS_FATAL_IF(mBlend || mMeshState || mScissor || mStencil,
34            "State object lifecycle not managed correctly");
35}
36
37void RenderState::onGLContextCreated() {
38    LOG_ALWAYS_FATAL_IF(mBlend || mMeshState || mScissor || mStencil,
39            "State object lifecycle not managed correctly");
40    mBlend = new Blend();
41    mMeshState = new MeshState();
42    mScissor = new Scissor();
43    mStencil = new Stencil();
44
45    // This is delayed because the first access of Caches makes GL calls
46    mCaches = &Caches::createInstance(*this);
47    mCaches->init();
48    mCaches->textureCache.setAssetAtlas(&mAssetAtlas);
49}
50
51static void layerLostGlContext(Layer* layer) {
52    layer->onGlContextLost();
53}
54
55void RenderState::onGLContextDestroyed() {
56/*
57    size_t size = mActiveLayers.size();
58    if (CC_UNLIKELY(size != 0)) {
59        ALOGE("Crashing, have %d contexts and %d layers at context destruction. isempty %d",
60                mRegisteredContexts.size(), size, mActiveLayers.empty());
61        mCaches->dumpMemoryUsage();
62        for (std::set<renderthread::CanvasContext*>::iterator cit = mRegisteredContexts.begin();
63                cit != mRegisteredContexts.end(); cit++) {
64            renderthread::CanvasContext* context = *cit;
65            ALOGE("Context: %p (root = %p)", context, context->mRootRenderNode.get());
66            ALOGE("  Prefeteched layers: %zu", context->mPrefetechedLayers.size());
67            for (std::set<RenderNode*>::iterator pit = context->mPrefetechedLayers.begin();
68                    pit != context->mPrefetechedLayers.end(); pit++) {
69                (*pit)->debugDumpLayers("    ");
70            }
71            context->mRootRenderNode->debugDumpLayers("  ");
72        }
73
74
75        if (mActiveLayers.begin() == mActiveLayers.end()) {
76            ALOGE("set has become empty. wat.");
77        }
78        for (std::set<const Layer*>::iterator lit = mActiveLayers.begin();
79             lit != mActiveLayers.end(); lit++) {
80            const Layer* layer = *(lit);
81            ALOGE("Layer %p, state %d, texlayer %d, fbo %d, buildlayered %d",
82                    layer, layer->state, layer->isTextureLayer(), layer->getFbo(), layer->wasBuildLayered);
83        }
84        LOG_ALWAYS_FATAL("%d layers have survived gl context destruction", size);
85    }
86*/
87
88    // TODO: reset all cached state in state objects
89    std::for_each(mActiveLayers.begin(), mActiveLayers.end(), layerLostGlContext);
90    mAssetAtlas.terminate();
91
92    mCaches->terminate();
93
94    delete mBlend;
95    mBlend = nullptr;
96    delete mMeshState;
97    mMeshState = nullptr;
98    delete mScissor;
99    mScissor = nullptr;
100    delete mStencil;
101    mStencil = nullptr;
102}
103
104void RenderState::setViewport(GLsizei width, GLsizei height) {
105    mViewportWidth = width;
106    mViewportHeight = height;
107    glViewport(0, 0, mViewportWidth, mViewportHeight);
108}
109
110
111void RenderState::getViewport(GLsizei* outWidth, GLsizei* outHeight) {
112    *outWidth = mViewportWidth;
113    *outHeight = mViewportHeight;
114}
115
116void RenderState::bindFramebuffer(GLuint fbo) {
117    if (mFramebuffer != fbo) {
118        mFramebuffer = fbo;
119        glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
120    }
121}
122
123void RenderState::invokeFunctor(Functor* functor, DrawGlInfo::Mode mode, DrawGlInfo* info) {
124    interruptForFunctorInvoke();
125    (*functor)(mode, info);
126    resumeFromFunctorInvoke();
127}
128
129void RenderState::interruptForFunctorInvoke() {
130    mCaches->setProgram(nullptr);
131    mCaches->textureState().resetActiveTexture();
132    meshState().unbindMeshBuffer();
133    meshState().unbindIndicesBuffer();
134    meshState().resetVertexPointers();
135    meshState().disableTexCoordsVertexArray();
136    debugOverdraw(false, false);
137}
138
139void RenderState::resumeFromFunctorInvoke() {
140    glViewport(0, 0, mViewportWidth, mViewportHeight);
141    glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
142    debugOverdraw(false, false);
143
144    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
145
146    scissor().invalidate();
147    blend().invalidate();
148
149    mCaches->textureState().activateTexture(0);
150    mCaches->textureState().resetBoundTextures();
151}
152
153void RenderState::debugOverdraw(bool enable, bool clear) {
154    if (mCaches->debugOverdraw && mFramebuffer == 0) {
155        if (clear) {
156            scissor().setEnabled(false);
157            stencil().clear();
158        }
159        if (enable) {
160            stencil().enableDebugWrite();
161        } else {
162            stencil().disable();
163        }
164    }
165}
166
167void RenderState::requireGLContext() {
168    assertOnGLThread();
169    mRenderThread.eglManager().requireGlContext();
170}
171
172void RenderState::assertOnGLThread() {
173    pthread_t curr = pthread_self();
174    LOG_ALWAYS_FATAL_IF(!pthread_equal(mThreadId, curr), "Wrong thread!");
175}
176
177class DecStrongTask : public renderthread::RenderTask {
178public:
179    DecStrongTask(VirtualLightRefBase* object) : mObject(object) {}
180
181    virtual void run() override {
182        mObject->decStrong(nullptr);
183        mObject = nullptr;
184        delete this;
185    }
186
187private:
188    VirtualLightRefBase* mObject;
189};
190
191void RenderState::postDecStrong(VirtualLightRefBase* object) {
192    mRenderThread.queue(new DecStrongTask(object));
193}
194
195///////////////////////////////////////////////////////////////////////////////
196// Render
197///////////////////////////////////////////////////////////////////////////////
198
199/*
200 * Not yet supported:
201 *
202 * Textures + coordinates
203 * SkiaShader
204 * ColorFilter
205 *
206    // TODO: texture coord
207    // TODO: texture support
208    // TODO: skiashader support
209    // TODO: color filter support
210 */
211
212void RenderState::render(const Glop& glop) {
213    const Glop::Mesh& mesh = glop.mesh;
214    const Glop::Fill& shader = glop.fill;
215
216    // ---------- Shader + uniform setup ----------
217    mCaches->setProgram(shader.program);
218
219    Glop::Fill::Color color = shader.color;
220    shader.program->setColor(color.r, color.g, color.b, color.a);
221
222    shader.program->set(glop.transform.ortho,
223            glop.transform.modelView,
224            glop.transform.canvas,
225            glop.transform.offset);
226
227    // ---------- Mesh setup ----------
228    if (glop.mesh.vertexFlags & kTextureCoord_Attrib) {
229        // TODO: support textures
230        LOG_ALWAYS_FATAL("textures not yet supported");
231    } else {
232        meshState().disableTexCoordsVertexArray();
233    }
234    if (glop.mesh.vertexFlags & kColor_Attrib) {
235        LOG_ALWAYS_FATAL("color attribute not yet supported");
236        // TODO: enable color, disable when done
237    }
238    if (glop.mesh.vertexFlags & kAlpha_Attrib) {
239        LOG_ALWAYS_FATAL("alpha attribute not yet supported");
240        // TODO: enable alpha attribute, disable when done
241    }
242
243    /**
244    * Hard-coded vertex assumptions:
245     *     - required
246     *     - xy floats
247     *     - 0 offset
248     *     - in VBO
249     */
250    bool force = meshState().bindMeshBuffer(mesh.vertexBufferObject);
251    meshState().bindPositionVertexPointer(force, nullptr, mesh.stride);
252
253    /**
254     * Hard-coded index assumptions:
255     *     - optional
256     *     - 0 offset
257     *     - in IBO
258     */
259    meshState().bindIndicesBufferInternal(mesh.indexBufferObject);
260
261    // ---------- GL state setup ----------
262    blend().setFactors(glop.blend.src, glop.blend.dst);
263
264    if (mesh.indexBufferObject) {
265        glDrawElements(glop.mesh.primitiveMode, glop.mesh.vertexCount, GL_UNSIGNED_BYTE, nullptr);
266    } else {
267        glDrawArrays(GL_TRIANGLE_STRIP, 0, glop.mesh.vertexCount);
268    }
269}
270
271} /* namespace uirenderer */
272} /* namespace android */
273