rsProgramVertex.cpp revision 479e2924807e1fff79de2e0bee2a67939d8659ee
1/*
2 * Copyright (C) 2009 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
17#ifndef ANDROID_RS_BUILD_FOR_HOST
18#include "rsContext.h"
19#include <GLES/gl.h>
20#include <GLES/glext.h>
21#include <GLES2/gl2.h>
22#include <GLES2/gl2ext.h>
23#else
24#include "rsContextHostStub.h"
25#include <OpenGL/gl.h>
26#include <OpenGL/glext.h>
27#endif //ANDROID_RS_BUILD_FOR_HOST
28
29#include "rsProgramVertex.h"
30
31using namespace android;
32using namespace android::renderscript;
33
34
35ProgramVertex::ProgramVertex(Context *rsc, bool texMat) :
36    Program(rsc)
37{
38    mAllocFile = __FILE__;
39    mAllocLine = __LINE__;
40    mTextureMatrixEnable = texMat;
41    mLightCount = 0;
42    init(rsc);
43}
44
45ProgramVertex::ProgramVertex(Context *rsc, const char * shaderText,
46                             uint32_t shaderLength, const uint32_t * params,
47                             uint32_t paramLength) :
48    Program(rsc, shaderText, shaderLength, params, paramLength)
49{
50    mAllocFile = __FILE__;
51    mAllocLine = __LINE__;
52    mTextureMatrixEnable = false;
53    mLightCount = 0;
54
55    init(rsc);
56}
57
58ProgramVertex::~ProgramVertex()
59{
60}
61
62static void logMatrix(const char *txt, const float *f)
63{
64    LOGV("Matrix %s, %p", txt, f);
65    LOGV("%6.4f, %6.4f, %6.4f, %6.4f", f[0], f[4], f[8], f[12]);
66    LOGV("%6.4f, %6.4f, %6.4f, %6.4f", f[1], f[5], f[9], f[13]);
67    LOGV("%6.4f, %6.4f, %6.4f, %6.4f", f[2], f[6], f[10], f[14]);
68    LOGV("%6.4f, %6.4f, %6.4f, %6.4f", f[3], f[7], f[11], f[15]);
69}
70
71void ProgramVertex::setupGL(const Context *rsc, ProgramVertexState *state)
72{
73    if ((state->mLast.get() == this) && !mDirty) {
74        return;
75    }
76    state->mLast.set(this);
77
78    const float *f = static_cast<const float *>(mConstants[0]->getPtr());
79
80    glMatrixMode(GL_TEXTURE);
81    if (mTextureMatrixEnable) {
82        glLoadMatrixf(&f[RS_PROGRAM_VERTEX_TEXTURE_OFFSET]);
83    } else {
84        glLoadIdentity();
85    }
86
87    glMatrixMode(GL_MODELVIEW);
88    glLoadIdentity();
89    if (mLightCount) {
90#ifndef ANDROID_RS_BUILD_FOR_HOST // GLES Only
91        int v = 0;
92        glEnable(GL_LIGHTING);
93
94        glLightModelxv(GL_LIGHT_MODEL_TWO_SIDE, &v);
95
96        for (uint32_t ct = 0; ct < mLightCount; ct++) {
97            const Light *l = mLights[ct].get();
98            glEnable(GL_LIGHT0 + ct);
99            l->setupGL(ct);
100        }
101        for (uint32_t ct = mLightCount; ct < MAX_LIGHTS; ct++) {
102            glDisable(GL_LIGHT0 + ct);
103        }
104#endif //ANDROID_RS_BUILD_FOR_HOST
105    } else {
106        glDisable(GL_LIGHTING);
107    }
108
109    if (!f) {
110        LOGE("Must bind constants to vertex program");
111    }
112
113    glMatrixMode(GL_PROJECTION);
114    glLoadMatrixf(&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET]);
115    glMatrixMode(GL_MODELVIEW);
116    glLoadMatrixf(&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET]);
117
118    mDirty = false;
119}
120
121void ProgramVertex::loadShader(Context *rsc) {
122    Program::loadShader(rsc, GL_VERTEX_SHADER);
123}
124
125void ProgramVertex::createShader()
126{
127    mShader.setTo("");
128
129    mShader.append("varying vec4 varColor;\n");
130    mShader.append("varying vec4 varTex0;\n");
131
132    if (mUserShader.length() > 1) {
133        mShader.append("uniform mat4 ");
134        mShader.append(mUniformNames[0]);
135        mShader.append(";\n");
136
137        for (uint32_t ct=0; ct < mConstantCount; ct++) {
138            const Element *e = mConstantTypes[ct]->getElement();
139            for (uint32_t field=0; field < e->getFieldCount(); field++) {
140                const Element *f = e->getField(field);
141                const char *fn = e->getFieldName(field);
142
143                if (fn[0] == '#') {
144                    continue;
145                }
146
147                // Cannot be complex
148                rsAssert(!f->getFieldCount());
149                switch(f->getComponent().getVectorSize()) {
150                case 1: mShader.append("uniform float UNI_"); break;
151                case 2: mShader.append("uniform vec2 UNI_"); break;
152                case 3: mShader.append("uniform vec3 UNI_"); break;
153                case 4: mShader.append("uniform vec4 UNI_"); break;
154                default:
155                    rsAssert(0);
156                }
157
158                mShader.append(fn);
159                mShader.append(";\n");
160            }
161        }
162
163
164        for (uint32_t ct=0; ct < mInputCount; ct++) {
165            const Element *e = mInputElements[ct].get();
166            for (uint32_t field=0; field < e->getFieldCount(); field++) {
167                const Element *f = e->getField(field);
168                const char *fn = e->getFieldName(field);
169
170                if (fn[0] == '#') {
171                    continue;
172                }
173
174                // Cannot be complex
175                rsAssert(!f->getFieldCount());
176                switch(f->getComponent().getVectorSize()) {
177                case 1: mShader.append("attribute float ATTRIB_"); break;
178                case 2: mShader.append("attribute vec2 ATTRIB_"); break;
179                case 3: mShader.append("attribute vec3 ATTRIB_"); break;
180                case 4: mShader.append("attribute vec4 ATTRIB_"); break;
181                default:
182                    rsAssert(0);
183                }
184
185                mShader.append(fn);
186                mShader.append(";\n");
187            }
188        }
189        mShader.append(mUserShader);
190    } else {
191        mShader.append("attribute vec4 ATTRIB_position;\n");
192        mShader.append("attribute vec4 ATTRIB_color;\n");
193        mShader.append("attribute vec3 ATTRIB_normal;\n");
194        mShader.append("attribute vec4 ATTRIB_texture0;\n");
195
196        for (uint32_t ct=0; ct < mUniformCount; ct++) {
197            mShader.append("uniform mat4 ");
198            mShader.append(mUniformNames[ct]);
199            mShader.append(";\n");
200        }
201
202        mShader.append("void main() {\n");
203        mShader.append("  gl_Position = UNI_MVP * ATTRIB_position;\n");
204        mShader.append("  gl_PointSize = 1.0;\n");
205
206        mShader.append("  varColor = ATTRIB_color;\n");
207        if (mTextureMatrixEnable) {
208            mShader.append("  varTex0 = UNI_TexMatrix * ATTRIB_texture0;\n");
209        } else {
210            mShader.append("  varTex0 = ATTRIB_texture0;\n");
211        }
212        mShader.append("}\n");
213    }
214}
215
216void ProgramVertex::setupGL2(const Context *rsc, ProgramVertexState *state, ShaderCache *sc)
217{
218    //LOGE("sgl2 vtx1 %x", glGetError());
219    if ((state->mLast.get() == this) && !mDirty) {
220        return;
221    }
222
223    rsc->checkError("ProgramVertex::setupGL2 start");
224    glVertexAttrib4f(1, state->color[0], state->color[1], state->color[2], state->color[3]);
225
226    const float *f = static_cast<const float *>(mConstants[0]->getPtr());
227
228    Matrix mvp;
229    mvp.load(&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET]);
230    Matrix t;
231    t.load(&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET]);
232    mvp.multiply(&t);
233
234    glUniformMatrix4fv(sc->vtxUniformSlot(0), 1, GL_FALSE, mvp.m);
235    if (mTextureMatrixEnable) {
236        glUniformMatrix4fv(sc->vtxUniformSlot(1), 1, GL_FALSE,
237                           &f[RS_PROGRAM_VERTEX_TEXTURE_OFFSET]);
238    }
239
240    rsc->checkError("ProgramVertex::setupGL2 begin uniforms");
241    uint32_t uidx = 1;
242    for (uint32_t ct=0; ct < mConstantCount; ct++) {
243        Allocation *alloc = mConstants[ct+1].get();
244        if (!alloc) {
245            continue;
246        }
247
248        const uint8_t *data = static_cast<const uint8_t *>(alloc->getPtr());
249        const Element *e = mConstantTypes[ct]->getElement();
250        for (uint32_t field=0; field < e->getFieldCount(); field++) {
251            const Element *f = e->getField(field);
252            uint32_t offset = e->getFieldOffsetBytes(field);
253            int32_t slot = sc->vtxUniformSlot(uidx);
254
255            const float *fd = reinterpret_cast<const float *>(&data[offset]);
256
257            //LOGE("Uniform  slot=%i, offset=%i, constant=%i, field=%i, uidx=%i", slot, offset, ct, field, uidx);
258            if (slot >= 0) {
259                switch(f->getComponent().getVectorSize()) {
260                case 1:
261                    //LOGE("Uniform 1 = %f", fd[0]);
262                    glUniform1fv(slot, 1, fd);
263                    break;
264                case 2:
265                    //LOGE("Uniform 2 = %f %f", fd[0], fd[1]);
266                    glUniform2fv(slot, 1, fd);
267                    break;
268                case 3:
269                    //LOGE("Uniform 3 = %f %f %f", fd[0], fd[1], fd[2]);
270                    glUniform3fv(slot, 1, fd);
271                    break;
272                case 4:
273                    //LOGE("Uniform 4 = %f %f %f %f", fd[0], fd[1], fd[2], fd[3]);
274                    glUniform4fv(slot, 1, fd);
275                    break;
276                default:
277                    rsAssert(0);
278                }
279            }
280            uidx ++;
281        }
282    }
283
284    for (uint32_t ct=0; ct < mConstantCount; ct++) {
285        uint32_t glSlot = sc->vtxUniformSlot(ct + 1);
286
287    }
288
289    state->mLast.set(this);
290    rsc->checkError("ProgramVertex::setupGL2");
291}
292
293void ProgramVertex::addLight(const Light *l)
294{
295    if (mLightCount < MAX_LIGHTS) {
296        mLights[mLightCount].set(l);
297        mLightCount++;
298    }
299}
300
301void ProgramVertex::setProjectionMatrix(const rsc_Matrix *m) const
302{
303    float *f = static_cast<float *>(mConstants[0]->getPtr());
304    memcpy(&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET], m, sizeof(rsc_Matrix));
305    mDirty = true;
306}
307
308void ProgramVertex::setModelviewMatrix(const rsc_Matrix *m) const
309{
310    float *f = static_cast<float *>(mConstants[0]->getPtr());
311    memcpy(&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET], m, sizeof(rsc_Matrix));
312    mDirty = true;
313}
314
315void ProgramVertex::setTextureMatrix(const rsc_Matrix *m) const
316{
317    float *f = static_cast<float *>(mConstants[0]->getPtr());
318    memcpy(&f[RS_PROGRAM_VERTEX_TEXTURE_OFFSET], m, sizeof(rsc_Matrix));
319    mDirty = true;
320}
321
322void ProgramVertex::transformToScreen(const Context *rsc, float *v4out, const float *v3in) const
323{
324    float *f = static_cast<float *>(mConstants[0]->getPtr());
325    Matrix mvp;
326    mvp.loadMultiply((Matrix *)&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET],
327                     (Matrix *)&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET]);
328    mvp.vectorMultiply(v4out, v3in);
329}
330
331void ProgramVertex::initAddUserElement(const Element *e, String8 *names, uint32_t *count, const char *prefix)
332{
333    rsAssert(e->getFieldCount());
334    for (uint32_t ct=0; ct < e->getFieldCount(); ct++) {
335        const Element *ce = e->getField(ct);
336        if (ce->getFieldCount()) {
337            initAddUserElement(ce, names, count, prefix);
338        } else {
339            String8 tmp(prefix);
340            tmp.append(e->getFieldName(ct));
341            names[*count].setTo(tmp.string());
342            (*count)++;
343        }
344    }
345}
346
347
348void ProgramVertex::init(Context *rsc)
349{
350    mAttribCount = 0;
351    if (mUserShader.size() > 0) {
352        for (uint32_t ct=0; ct < mInputCount; ct++) {
353            initAddUserElement(mInputElements[ct].get(), mAttribNames, &mAttribCount, "ATTRIB_");
354        }
355
356        mUniformCount = 1;
357        mUniformNames[0].setTo("UNI_MVP");
358        for (uint32_t ct=0; ct < mConstantCount; ct++) {
359            initAddUserElement(mConstantTypes[ct]->getElement(), mUniformNames, &mUniformCount, "UNI_");
360        }
361    } else {
362        mUniformCount = 2;
363        mUniformNames[0].setTo("UNI_MVP");
364        mUniformNames[1].setTo("UNI_TexMatrix");
365    }
366
367    createShader();
368}
369
370void ProgramVertex::serialize(OStream *stream) const
371{
372
373}
374
375ProgramVertex *ProgramVertex::createFromStream(Context *rsc, IStream *stream)
376{
377    return NULL;
378}
379
380
381///////////////////////////////////////////////////////////////////////
382
383ProgramVertexState::ProgramVertexState()
384{
385}
386
387ProgramVertexState::~ProgramVertexState()
388{
389}
390
391void ProgramVertexState::init(Context *rsc)
392{
393#ifndef ANDROID_RS_BUILD_FOR_HOST
394    RsElement e = (RsElement) Element::create(rsc, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 1);
395
396    rsi_TypeBegin(rsc, e);
397    rsi_TypeAdd(rsc, RS_DIMENSION_X, 48);
398    mAllocType.set((Type *)rsi_TypeCreate(rsc));
399
400    ProgramVertex *pv = new ProgramVertex(rsc, false);
401    Allocation *alloc = (Allocation *)rsi_AllocationCreateTyped(rsc, mAllocType.get());
402
403    mDefaultAlloc.set(alloc);
404    mDefault.set(pv);
405    pv->init(rsc);
406    pv->bindAllocation(alloc, 0);
407
408    color[0] = 1.f;
409    color[1] = 1.f;
410    color[2] = 1.f;
411    color[3] = 1.f;
412
413    updateSize(rsc);
414#endif //ANDROID_RS_BUILD_FOR_HOST
415
416}
417
418void ProgramVertexState::updateSize(Context *rsc)
419{
420    Matrix m;
421    m.loadOrtho(0,rsc->getWidth(), rsc->getHeight(),0, -1,1);
422    mDefaultAlloc->subData(RS_PROGRAM_VERTEX_PROJECTION_OFFSET, 16, &m.m[0], 16*4);
423
424    m.loadIdentity();
425    mDefaultAlloc->subData(RS_PROGRAM_VERTEX_MODELVIEW_OFFSET, 16, &m.m[0], 16*4);
426}
427
428void ProgramVertexState::deinit(Context *rsc)
429{
430    mDefaultAlloc.clear();
431    mDefault.clear();
432    mAllocType.clear();
433    mLast.clear();
434}
435
436
437namespace android {
438namespace renderscript {
439
440
441RsProgramVertex rsi_ProgramVertexCreate(Context *rsc, bool texMat)
442{
443    ProgramVertex *pv = new ProgramVertex(rsc, texMat);
444    pv->incUserRef();
445    return pv;
446}
447
448RsProgramVertex rsi_ProgramVertexCreate2(Context *rsc, const char * shaderText,
449                             uint32_t shaderLength, const uint32_t * params,
450                             uint32_t paramLength)
451{
452    ProgramVertex *pv = new ProgramVertex(rsc, shaderText, shaderLength, params, paramLength);
453    pv->incUserRef();
454    return pv;
455}
456
457
458}
459}
460