rsProgramVertex.cpp revision 5e9811f075f5a96925785a95afeda22592a840ac
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 float ATTRIB_pointSize;\n");
195        mShader.append("attribute vec4 ATTRIB_texture0;\n");
196
197        for (uint32_t ct=0; ct < mUniformCount; ct++) {
198            mShader.append("uniform mat4 ");
199            mShader.append(mUniformNames[ct]);
200            mShader.append(";\n");
201        }
202
203        mShader.append("void main() {\n");
204        mShader.append("  gl_Position = UNI_MVP * ATTRIB_position;\n");
205        mShader.append("  gl_PointSize = ATTRIB_pointSize;\n");
206
207        mShader.append("  varColor = ATTRIB_color;\n");
208        if (mTextureMatrixEnable) {
209            mShader.append("  varTex0 = UNI_TexMatrix * ATTRIB_texture0;\n");
210        } else {
211            mShader.append("  varTex0 = ATTRIB_texture0;\n");
212        }
213        //mShader.append("  pos.x = pos.x / 480.0;\n");
214        //mShader.append("  pos.y = pos.y / 800.0;\n");
215        //mShader.append("  gl_Position = pos;\n");
216        mShader.append("}\n");
217    }
218}
219
220void ProgramVertex::setupGL2(const Context *rsc, ProgramVertexState *state, ShaderCache *sc)
221{
222    //LOGE("sgl2 vtx1 %x", glGetError());
223    if ((state->mLast.get() == this) && !mDirty) {
224        //return;
225    }
226
227    rsc->checkError("ProgramVertex::setupGL2 start");
228    glVertexAttrib4f(1, state->color[0], state->color[1], state->color[2], state->color[3]);
229
230    const float *f = static_cast<const float *>(mConstants[0]->getPtr());
231
232    Matrix mvp;
233    mvp.load(&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET]);
234    Matrix t;
235    t.load(&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET]);
236    mvp.multiply(&t);
237
238    glUniformMatrix4fv(sc->vtxUniformSlot(0), 1, GL_FALSE, mvp.m);
239    if (mTextureMatrixEnable) {
240        glUniformMatrix4fv(sc->vtxUniformSlot(1), 1, GL_FALSE,
241                           &f[RS_PROGRAM_VERTEX_TEXTURE_OFFSET]);
242    }
243
244    rsc->checkError("ProgramVertex::setupGL2 begin uniforms");
245    uint32_t uidx = 1;
246    for (uint32_t ct=0; ct < mConstantCount; ct++) {
247        Allocation *alloc = mConstants[ct+1].get();
248        if (!alloc) {
249            continue;
250        }
251
252        const uint8_t *data = static_cast<const uint8_t *>(alloc->getPtr());
253        const Element *e = mConstantTypes[ct]->getElement();
254        for (uint32_t field=0; field < e->getFieldCount(); field++) {
255            const Element *f = e->getField(field);
256            uint32_t offset = e->getFieldOffsetBytes(field);
257            int32_t slot = sc->vtxUniformSlot(uidx);
258
259            const float *fd = reinterpret_cast<const float *>(&data[offset]);
260
261            //LOGE("Uniform  slot=%i, offset=%i, constant=%i, field=%i, uidx=%i", slot, offset, ct, field, uidx);
262            if (slot >= 0) {
263                switch(f->getComponent().getVectorSize()) {
264                case 1:
265                    //LOGE("Uniform 1 = %f", fd[0]);
266                    glUniform1fv(slot, 1, fd);
267                    break;
268                case 2:
269                    //LOGE("Uniform 2 = %f %f", fd[0], fd[1]);
270                    glUniform2fv(slot, 1, fd);
271                    break;
272                case 3:
273                    //LOGE("Uniform 3 = %f %f %f", fd[0], fd[1], fd[2]);
274                    glUniform3fv(slot, 1, fd);
275                    break;
276                case 4:
277                    //LOGE("Uniform 4 = %f %f %f %f", fd[0], fd[1], fd[2], fd[3]);
278                    glUniform4fv(slot, 1, fd);
279                    break;
280                default:
281                    rsAssert(0);
282                }
283            }
284            uidx ++;
285        }
286    }
287
288    for (uint32_t ct=0; ct < mConstantCount; ct++) {
289        uint32_t glSlot = sc->vtxUniformSlot(ct + 1);
290
291    }
292
293    state->mLast.set(this);
294    rsc->checkError("ProgramVertex::setupGL2");
295}
296
297void ProgramVertex::addLight(const Light *l)
298{
299    if (mLightCount < MAX_LIGHTS) {
300        mLights[mLightCount].set(l);
301        mLightCount++;
302    }
303}
304
305void ProgramVertex::setProjectionMatrix(const rsc_Matrix *m) const
306{
307    float *f = static_cast<float *>(mConstants[0]->getPtr());
308    memcpy(&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET], m, sizeof(rsc_Matrix));
309    mDirty = true;
310}
311
312void ProgramVertex::setModelviewMatrix(const rsc_Matrix *m) const
313{
314    float *f = static_cast<float *>(mConstants[0]->getPtr());
315    memcpy(&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET], m, sizeof(rsc_Matrix));
316    mDirty = true;
317}
318
319void ProgramVertex::setTextureMatrix(const rsc_Matrix *m) const
320{
321    float *f = static_cast<float *>(mConstants[0]->getPtr());
322    memcpy(&f[RS_PROGRAM_VERTEX_TEXTURE_OFFSET], m, sizeof(rsc_Matrix));
323    mDirty = true;
324}
325
326void ProgramVertex::transformToScreen(const Context *rsc, float *v4out, const float *v3in) const
327{
328    float *f = static_cast<float *>(mConstants[0]->getPtr());
329    Matrix mvp;
330    mvp.loadMultiply((Matrix *)&f[RS_PROGRAM_VERTEX_MODELVIEW_OFFSET],
331                     (Matrix *)&f[RS_PROGRAM_VERTEX_PROJECTION_OFFSET]);
332    mvp.vectorMultiply(v4out, v3in);
333}
334
335void ProgramVertex::initAddUserElement(const Element *e, String8 *names, uint32_t *count, const char *prefix)
336{
337    rsAssert(e->getFieldCount());
338    for (uint32_t ct=0; ct < e->getFieldCount(); ct++) {
339        const Element *ce = e->getField(ct);
340        if (ce->getFieldCount()) {
341            initAddUserElement(ce, names, count, prefix);
342        } else {
343            String8 tmp(prefix);
344            tmp.append(e->getFieldName(ct));
345            names[*count].setTo(tmp.string());
346            (*count)++;
347        }
348    }
349}
350
351
352void ProgramVertex::init(Context *rsc)
353{
354    mAttribCount = 0;
355    if (mUserShader.size() > 0) {
356        for (uint32_t ct=0; ct < mInputCount; ct++) {
357            initAddUserElement(mInputElements[ct].get(), mAttribNames, &mAttribCount, "ATTRIB_");
358        }
359
360        mUniformCount = 1;
361        mUniformNames[0].setTo("UNI_MVP");
362        for (uint32_t ct=0; ct < mConstantCount; ct++) {
363            initAddUserElement(mConstantTypes[ct]->getElement(), mUniformNames, &mUniformCount, "UNI_");
364        }
365    } else {
366        mUniformCount = 2;
367        mUniformNames[0].setTo("UNI_MVP");
368        mUniformNames[1].setTo("UNI_TexMatrix");
369    }
370
371    createShader();
372}
373
374void ProgramVertex::serialize(OStream *stream) const
375{
376
377}
378
379ProgramVertex *ProgramVertex::createFromStream(Context *rsc, IStream *stream)
380{
381    return NULL;
382}
383
384
385///////////////////////////////////////////////////////////////////////
386
387ProgramVertexState::ProgramVertexState()
388{
389}
390
391ProgramVertexState::~ProgramVertexState()
392{
393}
394
395void ProgramVertexState::init(Context *rsc)
396{
397#ifndef ANDROID_RS_BUILD_FOR_HOST
398    RsElement e = (RsElement) Element::create(rsc, RS_TYPE_FLOAT_32, RS_KIND_USER, false, 1);
399
400    rsi_TypeBegin(rsc, e);
401    rsi_TypeAdd(rsc, RS_DIMENSION_X, 48);
402    mAllocType.set((Type *)rsi_TypeCreate(rsc));
403
404    ProgramVertex *pv = new ProgramVertex(rsc, false);
405    Allocation *alloc = (Allocation *)rsi_AllocationCreateTyped(rsc, mAllocType.get());
406
407    mDefaultAlloc.set(alloc);
408    mDefault.set(pv);
409    pv->init(rsc);
410    pv->bindAllocation(alloc, 0);
411
412    color[0] = 1.f;
413    color[1] = 1.f;
414    color[2] = 1.f;
415    color[3] = 1.f;
416
417    updateSize(rsc);
418#endif //ANDROID_RS_BUILD_FOR_HOST
419
420}
421
422void ProgramVertexState::updateSize(Context *rsc)
423{
424    Matrix m;
425    m.loadOrtho(0,rsc->getWidth(), rsc->getHeight(),0, -1,1);
426    mDefaultAlloc->subData(RS_PROGRAM_VERTEX_PROJECTION_OFFSET, 16, &m.m[0], 16*4);
427
428    m.loadIdentity();
429    mDefaultAlloc->subData(RS_PROGRAM_VERTEX_MODELVIEW_OFFSET, 16, &m.m[0], 16*4);
430}
431
432void ProgramVertexState::deinit(Context *rsc)
433{
434    mDefaultAlloc.clear();
435    mDefault.clear();
436    mAllocType.clear();
437    mLast.clear();
438}
439
440
441namespace android {
442namespace renderscript {
443
444
445RsProgramVertex rsi_ProgramVertexCreate(Context *rsc, bool texMat)
446{
447    ProgramVertex *pv = new ProgramVertex(rsc, texMat);
448    pv->incUserRef();
449    return pv;
450}
451
452RsProgramVertex rsi_ProgramVertexCreate2(Context *rsc, const char * shaderText,
453                             uint32_t shaderLength, const uint32_t * params,
454                             uint32_t paramLength)
455{
456    ProgramVertex *pv = new ProgramVertex(rsc, shaderText, shaderLength, params, paramLength);
457    pv->incUserRef();
458    return pv;
459}
460
461
462}
463}
464