rsProgram.cpp revision 383e5b1f68c321a77bfd7466fa1171a9bfab4a6f
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 <GLES2/gl2.h>
20#include <GLES2/gl2ext.h>
21#else
22#include "rsContextHostStub.h"
23#include <OpenGL/gl.h>
24#include <OpenGL/glext.h>
25#endif //ANDROID_RS_BUILD_FOR_HOST
26
27#include "rsProgram.h"
28
29using namespace android;
30using namespace android::renderscript;
31
32Program::Program(Context *rsc) : ObjectBase(rsc)
33{
34    mAllocFile = __FILE__;
35    mAllocLine = __LINE__;
36    mDirty = true;
37    mShaderID = 0;
38    mAttribCount = 0;
39    mUniformCount = 0;
40    mTextureCount = 0;
41
42    mTextures = NULL;
43    mSamplers = NULL;
44    mInputElements = NULL;
45    mOutputElements = NULL;
46    mConstantTypes = NULL;
47    mInputCount = 0;
48    mOutputCount = 0;
49    mConstantCount = 0;
50    mIsValid = false;
51    mIsInternal = false;
52}
53
54Program::Program(Context *rsc, const char * shaderText, uint32_t shaderLength,
55                 const uint32_t * params, uint32_t paramLength) :
56    ObjectBase(rsc)
57{
58    mAllocFile = __FILE__;
59    mAllocLine = __LINE__;
60    mDirty = true;
61    mShaderID = 0;
62    mAttribCount = 0;
63    mUniformCount = 0;
64    mTextureCount = 0;
65
66    mInputCount = 0;
67    mOutputCount = 0;
68    mConstantCount = 0;
69
70    for (uint32_t ct=0; ct < paramLength; ct+=2) {
71        if (params[ct] == RS_PROGRAM_PARAM_INPUT) {
72            mInputCount++;
73        }
74        if (params[ct] == RS_PROGRAM_PARAM_OUTPUT) {
75            mOutputCount++;
76        }
77        if (params[ct] == RS_PROGRAM_PARAM_CONSTANT) {
78            mConstantCount++;
79        }
80        if (params[ct] == RS_PROGRAM_PARAM_TEXTURE_COUNT) {
81            mTextureCount = params[ct+1];
82        }
83    }
84
85    mTextures = new ObjectBaseRef<Allocation>[mTextureCount];
86    mSamplers = new ObjectBaseRef<Sampler>[mTextureCount];
87    mInputElements = new ObjectBaseRef<Element>[mInputCount];
88    mOutputElements = new ObjectBaseRef<Element>[mOutputCount];
89    mConstantTypes = new ObjectBaseRef<Type>[mConstantCount];
90
91    uint32_t input = 0;
92    uint32_t output = 0;
93    uint32_t constant = 0;
94    for (uint32_t ct=0; ct < paramLength; ct+=2) {
95        if (params[ct] == RS_PROGRAM_PARAM_INPUT) {
96            mInputElements[input++].set(reinterpret_cast<Element *>(params[ct+1]));
97        }
98        if (params[ct] == RS_PROGRAM_PARAM_OUTPUT) {
99            mOutputElements[output++].set(reinterpret_cast<Element *>(params[ct+1]));
100        }
101        if (params[ct] == RS_PROGRAM_PARAM_CONSTANT) {
102            mConstantTypes[constant++].set(reinterpret_cast<Type *>(params[ct+1]));
103        }
104    }
105    mIsInternal = false;
106    uint32_t internalTokenLen = strlen(RS_SHADER_INTERNAL);
107    if(shaderLength > internalTokenLen &&
108       strncmp(RS_SHADER_INTERNAL, shaderText, internalTokenLen) == 0) {
109        mIsInternal = true;
110        shaderText += internalTokenLen;
111        shaderLength -= internalTokenLen;
112    }
113    mUserShader.setTo(shaderText, shaderLength);
114}
115
116Program::~Program()
117{
118    for (uint32_t ct=0; ct < MAX_UNIFORMS; ct++) {
119        bindAllocation(NULL, NULL, ct);
120    }
121
122    for (uint32_t ct=0; ct < mTextureCount; ct++) {
123        bindTexture(NULL, ct, NULL);
124        bindSampler(NULL, ct, NULL);
125    }
126    delete[] mTextures;
127    delete[] mSamplers;
128    delete[] mInputElements;
129    delete[] mOutputElements;
130    delete[] mConstantTypes;
131    mInputCount = 0;
132    mOutputCount = 0;
133    mConstantCount = 0;
134}
135
136
137void Program::bindAllocation(Context *rsc, Allocation *alloc, uint32_t slot)
138{
139    if (alloc != NULL) {
140        if (slot >= mConstantCount) {
141            LOGE("Attempt to bind alloc at slot %u, on shader id %u, but const count is %u",
142                 slot, (uint32_t)this, mConstantCount);
143            rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind allocation");
144            return;
145        }
146        if (!alloc->getType()->isEqual(mConstantTypes[slot].get())) {
147            LOGE("Attempt to bind alloc at slot %u, on shader id %u, but types mismatch",
148                 slot, (uint32_t)this);
149            rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind allocation");
150            return;
151        }
152    }
153    if (mConstants[slot].get() == alloc) {
154        return;
155    }
156    if (mConstants[slot].get()) {
157        mConstants[slot].get()->removeProgramToDirty(this);
158    }
159    mConstants[slot].set(alloc);
160    if (alloc) {
161        alloc->addProgramToDirty(this);
162    }
163    mDirty = true;
164}
165
166void Program::bindTexture(Context *rsc, uint32_t slot, Allocation *a)
167{
168    if (slot >= mTextureCount) {
169        LOGE("Attempt to bind texture to slot %u but tex count is %u", slot, mTextureCount);
170        rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind texture");
171        return;
172    }
173
174    //LOGE("bindtex %i %p", slot, a);
175    mTextures[slot].set(a);
176    mDirty = true;
177}
178
179void Program::bindSampler(Context *rsc, uint32_t slot, Sampler *s)
180{
181    if (slot >= mTextureCount) {
182        LOGE("Attempt to bind sampler to slot %u but tex count is %u", slot, mTextureCount);
183        rsc->setError(RS_ERROR_BAD_SHADER, "Cannot bind sampler");
184        return;
185    }
186
187    mSamplers[slot].set(s);
188    mDirty = true;
189}
190
191String8 Program::getGLSLInputString() const
192{
193    String8 s;
194    for (uint32_t ct=0; ct < mInputCount; ct++) {
195        const Element *e = mInputElements[ct].get();
196        for (uint32_t field=0; field < e->getFieldCount(); field++) {
197            const Element *f = e->getField(field);
198
199            // Cannot be complex
200            rsAssert(!f->getFieldCount());
201            switch(f->getComponent().getVectorSize()) {
202            case 1: s.append("attribute float ATTRIB_"); break;
203            case 2: s.append("attribute vec2 ATTRIB_"); break;
204            case 3: s.append("attribute vec3 ATTRIB_"); break;
205            case 4: s.append("attribute vec4 ATTRIB_"); break;
206            default:
207                rsAssert(0);
208            }
209
210            s.append(e->getFieldName(field));
211            s.append(";\n");
212        }
213    }
214    return s;
215}
216
217String8 Program::getGLSLOutputString() const
218{
219    return String8();
220}
221
222String8 Program::getGLSLConstantString() const
223{
224    return String8();
225}
226
227
228void Program::createShader()
229{
230}
231
232bool Program::loadShader(Context *rsc, uint32_t type)
233{
234    mShaderID = glCreateShader(type);
235    rsAssert(mShaderID);
236
237    if (rsc->props.mLogShaders) {
238        LOGV("Loading shader type %x, ID %i", type, mShaderID);
239        LOGV("%s", mShader.string());
240    }
241
242    if (mShaderID) {
243        const char * ss = mShader.string();
244        glShaderSource(mShaderID, 1, &ss, NULL);
245        glCompileShader(mShaderID);
246
247        GLint compiled = 0;
248        glGetShaderiv(mShaderID, GL_COMPILE_STATUS, &compiled);
249        if (!compiled) {
250            GLint infoLen = 0;
251            glGetShaderiv(mShaderID, GL_INFO_LOG_LENGTH, &infoLen);
252            if (infoLen) {
253                char* buf = (char*) malloc(infoLen);
254                if (buf) {
255                    glGetShaderInfoLog(mShaderID, infoLen, NULL, buf);
256                    LOGE("Could not compile shader \n%s\n", buf);
257                    free(buf);
258                }
259                glDeleteShader(mShaderID);
260                mShaderID = 0;
261                rsc->setError(RS_ERROR_BAD_SHADER, "Error returned from GL driver loading shader text,");
262                return false;
263            }
264        }
265    }
266
267    if (rsc->props.mLogShaders) {
268        LOGV("--Shader load result %x ", glGetError());
269    }
270    mIsValid = true;
271    return true;
272}
273
274void Program::setShader(const char *txt, uint32_t len)
275{
276    mUserShader.setTo(txt, len);
277}
278
279void Program::appendUserConstants() {
280    for (uint32_t ct=0; ct < mConstantCount; ct++) {
281        const Element *e = mConstantTypes[ct]->getElement();
282        for (uint32_t field=0; field < e->getFieldCount(); field++) {
283            const Element *f = e->getField(field);
284            const char *fn = e->getFieldName(field);
285
286            if (fn[0] == '#') {
287                continue;
288            }
289
290            // Cannot be complex
291            rsAssert(!f->getFieldCount());
292            if(f->getType() == RS_TYPE_MATRIX_4X4) {
293                mShader.append("uniform mat4 UNI_");
294            }
295            else if(f->getType() == RS_TYPE_MATRIX_3X3) {
296                mShader.append("uniform mat3 UNI_");
297            }
298            else if(f->getType() == RS_TYPE_MATRIX_2X2) {
299                mShader.append("uniform mat2 UNI_");
300            }
301            else {
302                switch(f->getComponent().getVectorSize()) {
303                case 1: mShader.append("uniform float UNI_"); break;
304                case 2: mShader.append("uniform vec2 UNI_"); break;
305                case 3: mShader.append("uniform vec3 UNI_"); break;
306                case 4: mShader.append("uniform vec4 UNI_"); break;
307                default:
308                    rsAssert(0);
309                }
310            }
311
312            mShader.append(fn);
313            mShader.append(";\n");
314        }
315    }
316}
317
318void Program::setupUserConstants(Context *rsc, ShaderCache *sc, bool isFragment) {
319    uint32_t uidx = 0;
320    for (uint32_t ct=0; ct < mConstantCount; ct++) {
321        Allocation *alloc = mConstants[ct].get();
322        if (!alloc) {
323            LOGE("Attempting to set constants on shader id %u, but alloc at slot %u is not set", (uint32_t)this, ct);
324            rsc->setError(RS_ERROR_BAD_SHADER, "No constant allocation bound");
325            continue;
326        }
327
328        const uint8_t *data = static_cast<const uint8_t *>(alloc->getPtr());
329        const Element *e = mConstantTypes[ct]->getElement();
330        for (uint32_t field=0; field < e->getFieldCount(); field++) {
331            const Element *f = e->getField(field);
332            const char *fieldName = e->getFieldName(field);
333            // If this field is padding, skip it
334            if(fieldName[0] == '#') {
335                continue;
336            }
337
338            uint32_t offset = e->getFieldOffsetBytes(field);
339            const float *fd = reinterpret_cast<const float *>(&data[offset]);
340
341            int32_t slot = -1;
342            if(!isFragment) {
343                slot = sc->vtxUniformSlot(uidx);
344            }
345            else {
346                slot = sc->fragUniformSlot(uidx);
347            }
348
349            //LOGE("Uniform  slot=%i, offset=%i, constant=%i, field=%i, uidx=%i, name=%s", slot, offset, ct, field, uidx, fieldName);
350            if (slot >= 0) {
351                if(f->getType() == RS_TYPE_MATRIX_4X4) {
352                    glUniformMatrix4fv(slot, 1, GL_FALSE, fd);
353                    /*for(int i = 0; i < 4; i++) {
354                        LOGE("Mat = %f %f %f %f", fd[i*4 + 0], fd[i*4 + 1], fd[i*4 + 2], fd[i*4 + 3]);
355                    }*/
356                }
357                else if(f->getType() == RS_TYPE_MATRIX_3X3) {
358                    glUniformMatrix3fv(slot, 1, GL_FALSE, fd);
359                }
360                else if(f->getType() == RS_TYPE_MATRIX_2X2) {
361                    glUniformMatrix2fv(slot, 1, GL_FALSE, fd);
362                }
363                else {
364                    switch(f->getComponent().getVectorSize()) {
365                    case 1:
366                        //LOGE("Uniform 1 = %f", fd[0]);
367                        glUniform1fv(slot, 1, fd);
368                        break;
369                    case 2:
370                        //LOGE("Uniform 2 = %f %f", fd[0], fd[1]);
371                        glUniform2fv(slot, 1, fd);
372                        break;
373                    case 3:
374                        //LOGE("Uniform 3 = %f %f %f", fd[0], fd[1], fd[2]);
375                        glUniform3fv(slot, 1, fd);
376                        break;
377                    case 4:
378                        //LOGE("Uniform 4 = %f %f %f %f", fd[0], fd[1], fd[2], fd[3]);
379                        glUniform4fv(slot, 1, fd);
380                        break;
381                    default:
382                        rsAssert(0);
383                    }
384                }
385            }
386            uidx ++;
387        }
388    }
389}
390
391void Program::initAddUserElement(const Element *e, String8 *names, uint32_t *count, const char *prefix)
392{
393    rsAssert(e->getFieldCount());
394    for (uint32_t ct=0; ct < e->getFieldCount(); ct++) {
395        const Element *ce = e->getField(ct);
396        if (ce->getFieldCount()) {
397            initAddUserElement(ce, names, count, prefix);
398        }
399        else if(e->getFieldName(ct)[0] != '#') {
400            String8 tmp(prefix);
401            tmp.append(e->getFieldName(ct));
402            names[*count].setTo(tmp.string());
403            (*count)++;
404        }
405    }
406}
407
408namespace android {
409namespace renderscript {
410
411
412void rsi_ProgramBindConstants(Context *rsc, RsProgram vp, uint32_t slot, RsAllocation constants)
413{
414    Program *p = static_cast<Program *>(vp);
415    p->bindAllocation(rsc, static_cast<Allocation *>(constants), slot);
416}
417
418void rsi_ProgramBindTexture(Context *rsc, RsProgram vpf, uint32_t slot, RsAllocation a)
419{
420    Program *p = static_cast<Program *>(vpf);
421    p->bindTexture(rsc, slot, static_cast<Allocation *>(a));
422}
423
424void rsi_ProgramBindSampler(Context *rsc, RsProgram vpf, uint32_t slot, RsSampler s)
425{
426    Program *p = static_cast<Program *>(vpf);
427    p->bindSampler(rsc, slot, static_cast<Sampler *>(s));
428}
429
430}
431}
432
433