rsProgramVertex.cpp revision 95333f998fd4a983f89e5128e85f6f710d200bd9
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
225    const float *f = static_cast<const float *>(mConstants[0]->getPtr());
226
227    Matrix mvp;
228    mvp.load(&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET]);
229    Matrix t;
230    t.load(&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET]);
231    mvp.multiply(&t);
232
233    glUniformMatrix4fv(sc->vtxUniformSlot(0), 1, GL_FALSE, mvp.m);
234    if (mTextureMatrixEnable) {
235        glUniformMatrix4fv(sc->vtxUniformSlot(1), 1, GL_FALSE,
236                           &f[RS_PROGRAM_VERTEX_TEXTURE_OFFSET]);
237    }
238
239    rsc->checkError("ProgramVertex::setupGL2 begin uniforms");
240    uint32_t uidx = 1;
241    for (uint32_t ct=0; ct < mConstantCount; ct++) {
242        Allocation *alloc = mConstants[ct+1].get();
243        if (!alloc) {
244            continue;
245        }
246
247        const uint8_t *data = static_cast<const uint8_t *>(alloc->getPtr());
248        const Element *e = mConstantTypes[ct]->getElement();
249        for (uint32_t field=0; field < e->getFieldCount(); field++) {
250            const Element *f = e->getField(field);
251            uint32_t offset = e->getFieldOffsetBytes(field);
252            int32_t slot = sc->vtxUniformSlot(uidx);
253
254            const float *fd = reinterpret_cast<const float *>(&data[offset]);
255
256            //LOGE("Uniform  slot=%i, offset=%i, constant=%i, field=%i, uidx=%i", slot, offset, ct, field, uidx);
257            if (slot >= 0) {
258                switch(f->getComponent().getVectorSize()) {
259                case 1:
260                    //LOGE("Uniform 1 = %f", fd[0]);
261                    glUniform1fv(slot, 1, fd);
262                    break;
263                case 2:
264                    //LOGE("Uniform 2 = %f %f", fd[0], fd[1]);
265                    glUniform2fv(slot, 1, fd);
266                    break;
267                case 3:
268                    //LOGE("Uniform 3 = %f %f %f", fd[0], fd[1], fd[2]);
269                    glUniform3fv(slot, 1, fd);
270                    break;
271                case 4:
272                    //LOGE("Uniform 4 = %f %f %f %f", fd[0], fd[1], fd[2], fd[3]);
273                    glUniform4fv(slot, 1, fd);
274                    break;
275                default:
276                    rsAssert(0);
277                }
278            }
279            uidx ++;
280        }
281    }
282
283    for (uint32_t ct=0; ct < mConstantCount; ct++) {
284        uint32_t glSlot = sc->vtxUniformSlot(ct + 1);
285
286    }
287
288    state->mLast.set(this);
289    rsc->checkError("ProgramVertex::setupGL2");
290}
291
292void ProgramVertex::addLight(const Light *l)
293{
294    if (mLightCount < MAX_LIGHTS) {
295        mLights[mLightCount].set(l);
296        mLightCount++;
297    }
298}
299
300void ProgramVertex::setProjectionMatrix(const rsc_Matrix *m) const
301{
302    float *f = static_cast<float *>(mConstants[0]->getPtr());
303    memcpy(&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET], m, sizeof(rsc_Matrix));
304    mDirty = true;
305}
306
307void ProgramVertex::setModelviewMatrix(const rsc_Matrix *m) const
308{
309    float *f = static_cast<float *>(mConstants[0]->getPtr());
310    memcpy(&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET], m, sizeof(rsc_Matrix));
311    mDirty = true;
312}
313
314void ProgramVertex::setTextureMatrix(const rsc_Matrix *m) const
315{
316    float *f = static_cast<float *>(mConstants[0]->getPtr());
317    memcpy(&f[RS_PROGRAM_VERTEX_TEXTURE_OFFSET], m, sizeof(rsc_Matrix));
318    mDirty = true;
319}
320
321void ProgramVertex::getProjectionMatrix(rsc_Matrix *m) const
322{
323    float *f = static_cast<float *>(mConstants[0]->getPtr());
324    memcpy(m, &f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET], sizeof(rsc_Matrix));
325}
326
327void ProgramVertex::transformToScreen(const Context *rsc, float *v4out, const float *v3in) const
328{
329    float *f = static_cast<float *>(mConstants[0]->getPtr());
330    Matrix mvp;
331    mvp.loadMultiply((Matrix *)&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET],
332                     (Matrix *)&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET]);
333    mvp.vectorMultiply(v4out, v3in);
334}
335
336void ProgramVertex::initAddUserElement(const Element *e, String8 *names, uint32_t *count, const char *prefix)
337{
338    rsAssert(e->getFieldCount());
339    for (uint32_t ct=0; ct < e->getFieldCount(); ct++) {
340        const Element *ce = e->getField(ct);
341        if (ce->getFieldCount()) {
342            initAddUserElement(ce, names, count, prefix);
343        } else {
344            String8 tmp(prefix);
345            tmp.append(e->getFieldName(ct));
346            names[*count].setTo(tmp.string());
347            (*count)++;
348        }
349    }
350}
351
352
353void ProgramVertex::init(Context *rsc)
354{
355    mAttribCount = 0;
356    if (mUserShader.size() > 0) {
357        for (uint32_t ct=0; ct < mInputCount; ct++) {
358            initAddUserElement(mInputElements[ct].get(), mAttribNames, &mAttribCount, "ATTRIB_");
359        }
360
361        mUniformCount = 1;
362        mUniformNames[0].setTo("UNI_MVP");
363        for (uint32_t ct=0; ct < mConstantCount; ct++) {
364            initAddUserElement(mConstantTypes[ct]->getElement(), mUniformNames, &mUniformCount, "UNI_");
365        }
366    } else {
367        mUniformCount = 2;
368        mUniformNames[0].setTo("UNI_MVP");
369        mUniformNames[1].setTo("UNI_TexMatrix");
370    }
371
372    createShader();
373}
374
375void ProgramVertex::serialize(OStream *stream) const
376{
377
378}
379
380ProgramVertex *ProgramVertex::createFromStream(Context *rsc, IStream *stream)
381{
382    return NULL;
383}
384
385
386///////////////////////////////////////////////////////////////////////
387
388ProgramVertexState::ProgramVertexState()
389{
390}
391
392ProgramVertexState::~ProgramVertexState()
393{
394}
395
396void ProgramVertexState::init(Context *rsc)
397{
398#ifndef ANDROID_RS_BUILD_FOR_HOST
399    RsElement e = (RsElement) Element::create(rsc, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 1);
400
401    rsi_TypeBegin(rsc, e);
402    rsi_TypeAdd(rsc, RS_DIMENSION_X, 48);
403    mAllocType.set((Type *)rsi_TypeCreate(rsc));
404
405    ProgramVertex *pv = new ProgramVertex(rsc, false);
406    Allocation *alloc = (Allocation *)rsi_AllocationCreateTyped(rsc, mAllocType.get());
407
408    mDefaultAlloc.set(alloc);
409    mDefault.set(pv);
410    pv->init(rsc);
411    pv->bindAllocation(alloc, 0);
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