RenderState.cpp revision 253f2c213f6ecda63b6872aee77bd30d5ec07c82
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}
56
57static void layerLostGlContext(Layer* layer) {
58    layer->onGlContextLost();
59}
60
61void RenderState::onGLContextDestroyed() {
62    mLayerPool.clear();
63
64    // TODO: reset all cached state in state objects
65    std::for_each(mActiveLayers.begin(), mActiveLayers.end(), layerLostGlContext);
66
67    mCaches->terminate();
68
69    delete mBlend;
70    mBlend = nullptr;
71    delete mMeshState;
72    mMeshState = nullptr;
73    delete mScissor;
74    mScissor = nullptr;
75    delete mStencil;
76    mStencil = nullptr;
77
78    GpuMemoryTracker::onGLContextDestroyed();
79}
80
81void RenderState::flush(Caches::FlushMode mode) {
82    switch (mode) {
83        case Caches::FlushMode::Full:
84            // fall through
85        case Caches::FlushMode::Moderate:
86            // fall through
87        case Caches::FlushMode::Layers:
88            mLayerPool.clear();
89            break;
90    }
91    mCaches->flush(mode);
92}
93
94void RenderState::setViewport(GLsizei width, GLsizei height) {
95    mViewportWidth = width;
96    mViewportHeight = height;
97    glViewport(0, 0, mViewportWidth, mViewportHeight);
98}
99
100
101void RenderState::getViewport(GLsizei* outWidth, GLsizei* outHeight) {
102    *outWidth = mViewportWidth;
103    *outHeight = mViewportHeight;
104}
105
106void RenderState::bindFramebuffer(GLuint fbo) {
107    if (mFramebuffer != fbo) {
108        mFramebuffer = fbo;
109        glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
110    }
111}
112
113GLuint RenderState::createFramebuffer() {
114    GLuint ret;
115    glGenFramebuffers(1, &ret);
116    return ret;
117}
118
119void RenderState::deleteFramebuffer(GLuint fbo) {
120    if (mFramebuffer == fbo) {
121        // GL defines that deleting the currently bound FBO rebinds FBO 0.
122        // Reflect this in our cached value.
123        mFramebuffer = 0;
124    }
125    glDeleteFramebuffers(1, &fbo);
126}
127
128void RenderState::invokeFunctor(Functor* functor, DrawGlInfo::Mode mode, DrawGlInfo* info) {
129    if (mode == DrawGlInfo::kModeProcessNoContext) {
130        // If there's no context we don't need to interrupt as there's
131        // no gl state to save/restore
132        (*functor)(mode, info);
133    } else {
134        interruptForFunctorInvoke();
135        (*functor)(mode, info);
136        resumeFromFunctorInvoke();
137    }
138}
139
140void RenderState::interruptForFunctorInvoke() {
141    mCaches->setProgram(nullptr);
142    mCaches->textureState().resetActiveTexture();
143    meshState().unbindMeshBuffer();
144    meshState().unbindIndicesBuffer();
145    meshState().resetVertexPointers();
146    meshState().disableTexCoordsVertexArray();
147    debugOverdraw(false, false);
148    // TODO: We need a way to know whether the functor is sRGB aware (b/32072673)
149    if (mCaches->extensions().hasSRGBWriteControl()) {
150        glDisable(GL_FRAMEBUFFER_SRGB_EXT);
151    }
152}
153
154void RenderState::resumeFromFunctorInvoke() {
155    if (mCaches->extensions().hasSRGBWriteControl()) {
156        glEnable(GL_FRAMEBUFFER_SRGB_EXT);
157    }
158
159    glViewport(0, 0, mViewportWidth, mViewportHeight);
160    glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
161    debugOverdraw(false, false);
162
163    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
164
165    scissor().invalidate();
166    blend().invalidate();
167
168    mCaches->textureState().activateTexture(0);
169    mCaches->textureState().resetBoundTextures();
170}
171
172void RenderState::debugOverdraw(bool enable, bool clear) {
173    if (Properties::debugOverdraw && mFramebuffer == 0) {
174        if (clear) {
175            scissor().setEnabled(false);
176            stencil().clear();
177        }
178        if (enable) {
179            stencil().enableDebugWrite();
180        } else {
181            stencil().disable();
182        }
183    }
184}
185
186class DecStrongTask : public renderthread::RenderTask {
187public:
188    explicit DecStrongTask(VirtualLightRefBase* object) : mObject(object) {}
189
190    virtual void run() override {
191        mObject->decStrong(nullptr);
192        mObject = nullptr;
193        delete this;
194    }
195
196private:
197    VirtualLightRefBase* mObject;
198};
199
200void RenderState::postDecStrong(VirtualLightRefBase* object) {
201    if (pthread_equal(mThreadId, pthread_self())) {
202        object->decStrong(nullptr);
203    } else {
204        mRenderThread.queue(new DecStrongTask(object));
205    }
206}
207
208///////////////////////////////////////////////////////////////////////////////
209// Render
210///////////////////////////////////////////////////////////////////////////////
211
212void RenderState::render(const Glop& glop, const Matrix4& orthoMatrix) {
213    const Glop::Mesh& mesh = glop.mesh;
214    const Glop::Mesh::Vertices& vertices = mesh.vertices;
215    const Glop::Mesh::Indices& indices = mesh.indices;
216    const Glop::Fill& fill = glop.fill;
217
218    GL_CHECKPOINT(MODERATE);
219
220    // ---------------------------------------------
221    // ---------- Program + uniform setup ----------
222    // ---------------------------------------------
223    mCaches->setProgram(fill.program);
224
225    if (fill.colorEnabled) {
226        fill.program->setColor(fill.color);
227    }
228
229    fill.program->set(orthoMatrix,
230            glop.transform.modelView,
231            glop.transform.meshTransform(),
232            glop.transform.transformFlags & TransformFlags::OffsetByFudgeFactor);
233
234    // Color filter uniforms
235    if (fill.filterMode == ProgramDescription::ColorFilterMode::Blend) {
236        const FloatColor& color = fill.filter.color;
237        glUniform4f(mCaches->program().getUniform("colorBlend"),
238                color.r, color.g, color.b, color.a);
239    } else if (fill.filterMode == ProgramDescription::ColorFilterMode::Matrix) {
240        glUniformMatrix4fv(mCaches->program().getUniform("colorMatrix"), 1, GL_FALSE,
241                fill.filter.matrix.matrix);
242        glUniform4fv(mCaches->program().getUniform("colorMatrixVector"), 1,
243                fill.filter.matrix.vector);
244    }
245
246    // Round rect clipping uniforms
247    if (glop.roundRectClipState) {
248        // TODO: avoid query, and cache values (or RRCS ptr) in program
249        const RoundRectClipState* state = glop.roundRectClipState;
250        const Rect& innerRect = state->innerRect;
251        glUniform4f(fill.program->getUniform("roundRectInnerRectLTRB"),
252                innerRect.left, innerRect.top,
253                innerRect.right, innerRect.bottom);
254        glUniformMatrix4fv(fill.program->getUniform("roundRectInvTransform"),
255                1, GL_FALSE, &state->matrix.data[0]);
256
257        // add half pixel to round out integer rect space to cover pixel centers
258        float roundedOutRadius = state->radius + 0.5f;
259        glUniform1f(fill.program->getUniform("roundRectRadius"),
260                roundedOutRadius);
261    }
262
263    GL_CHECKPOINT(MODERATE);
264
265    // --------------------------------
266    // ---------- Mesh setup ----------
267    // --------------------------------
268    // vertices
269    meshState().bindMeshBuffer(vertices.bufferObject);
270    meshState().bindPositionVertexPointer(vertices.position, vertices.stride);
271
272    // indices
273    meshState().bindIndicesBuffer(indices.bufferObject);
274
275    // texture
276    if (fill.texture.texture != nullptr) {
277        const Glop::Fill::TextureData& texture = fill.texture;
278        // texture always takes slot 0, shader samplers increment from there
279        mCaches->textureState().activateTexture(0);
280
281        mCaches->textureState().bindTexture(texture.target, texture.texture->id());
282        if (texture.clamp != GL_INVALID_ENUM) {
283            texture.texture->setWrap(texture.clamp, false, false, texture.target);
284        }
285        if (texture.filter != GL_INVALID_ENUM) {
286            texture.texture->setFilter(texture.filter, false, false, texture.target);
287        }
288
289        if (texture.textureTransform) {
290            glUniformMatrix4fv(fill.program->getUniform("mainTextureTransform"), 1,
291                    GL_FALSE, &texture.textureTransform->data[0]);
292        }
293    }
294
295    // vertex attributes (tex coord, color, alpha)
296    if (vertices.attribFlags & VertexAttribFlags::TextureCoord) {
297        meshState().enableTexCoordsVertexArray();
298        meshState().bindTexCoordsVertexPointer(vertices.texCoord, vertices.stride);
299    } else {
300        meshState().disableTexCoordsVertexArray();
301    }
302    int colorLocation = -1;
303    if (vertices.attribFlags & VertexAttribFlags::Color) {
304        colorLocation = fill.program->getAttrib("colors");
305        glEnableVertexAttribArray(colorLocation);
306        glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, vertices.stride, vertices.color);
307    }
308    int alphaLocation = -1;
309    if (vertices.attribFlags & VertexAttribFlags::Alpha) {
310        // NOTE: alpha vertex position is computed assuming no VBO
311        const void* alphaCoords = ((const GLbyte*) vertices.position) + kVertexAlphaOffset;
312        alphaLocation = fill.program->getAttrib("vtxAlpha");
313        glEnableVertexAttribArray(alphaLocation);
314        glVertexAttribPointer(alphaLocation, 1, GL_FLOAT, GL_FALSE, vertices.stride, alphaCoords);
315    }
316    // Shader uniforms
317    SkiaShader::apply(*mCaches, fill.skiaShaderData, mViewportWidth, mViewportHeight);
318
319    GL_CHECKPOINT(MODERATE);
320    Texture* texture = (fill.skiaShaderData.skiaShaderType & kBitmap_SkiaShaderType) ?
321            fill.skiaShaderData.bitmapData.bitmapTexture : nullptr;
322    const AutoTexture autoCleanup(texture);
323
324    // ------------------------------------
325    // ---------- GL state setup ----------
326    // ------------------------------------
327    blend().setFactors(glop.blend.src, glop.blend.dst);
328
329    GL_CHECKPOINT(MODERATE);
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            meshState().bindPositionVertexPointer(vertexData, vertices.stride);
342            if (vertices.attribFlags & VertexAttribFlags::TextureCoord) {
343                meshState().bindTexCoordsVertexPointer(
344                        vertexData + kMeshTextureOffset, vertices.stride);
345            }
346
347            glDrawElements(mesh.primitiveMode, drawCount, GL_UNSIGNED_SHORT, nullptr);
348            elementsCount -= drawCount;
349            vertexData += (drawCount / 6) * 4 * vertices.stride;
350        }
351    } else if (indices.bufferObject || indices.indices) {
352        glDrawElements(mesh.primitiveMode, mesh.elementCount, GL_UNSIGNED_SHORT, indices.indices);
353    } else {
354        glDrawArrays(mesh.primitiveMode, 0, mesh.elementCount);
355    }
356
357    GL_CHECKPOINT(MODERATE);
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    GL_CHECKPOINT(MODERATE);
370}
371
372void RenderState::dump() {
373    blend().dump();
374    meshState().dump();
375    scissor().dump();
376    stencil().dump();
377}
378
379} /* namespace uirenderer */
380} /* namespace android */
381