aboutsummaryrefslogtreecommitdiffstats
path: root/src/jogl/classes/com/jogamp/graph/curve/opengl/RenderState.java
blob: 818526cd73744f6d43541a94a578371c1ce7c3e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/**
 * Copyright 2011 JogAmp Community. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of JogAmp Community.
 */
package com.jogamp.graph.curve.opengl;

import java.nio.FloatBuffer;

import javax.media.opengl.GL;
import javax.media.opengl.GL2ES2;
import javax.media.opengl.GLException;
import javax.media.opengl.GLUniformData;

import jogamp.graph.curve.opengl.shader.UniformNames;

import com.jogamp.common.os.Platform;
import com.jogamp.graph.curve.Region;
import com.jogamp.graph.geom.Vertex;
import com.jogamp.opengl.util.GLArrayDataServer;
import com.jogamp.opengl.util.PMVMatrix;
import com.jogamp.opengl.util.glsl.ShaderProgram;

public class RenderState {
    private static final String thisKey = "jogamp.graph.curve.RenderState" ;

    /**
     * Bitfield hint, {@link #isHintMaskSet(int) if set}
     * stating <i>enabled</i> {@link GL#GL_BLEND}, otherwise <i>disabled</i>.
     * <p>
     * Shall be set via {@link #setHintMask(int)} and cleared via {@link #clearHintMask(int)}.
     * </p>
     * <p>
     * Due to alpha blending and multipass rendering, e.g. {@link Region#VBAA_RENDERING_BIT},
     * the clear-color shall be set to the {@link #getColorStaticUniform() foreground color} and <i>zero alpha</i>,
     * otherwise blending will amplify the scene's clear-color.
     * </p>
     * <p>
     * Shall be called by custom code, e.g. via {@link RegionRenderer}'s
     * enable and disable {@link RegionRenderer.GLCallback} as done in
     * {@link RegionRenderer#defaultBlendEnable} and {@link RegionRenderer#defaultBlendDisable}.
     * </p>
     */
    public static final int BITHINT_BLENDING_ENABLED = 1 << 0 ;

    public static RenderState createRenderState(Vertex.Factory<? extends Vertex> pointFactory) {
        return new RenderState(pointFactory, null);
    }

    public static RenderState createRenderState(Vertex.Factory<? extends Vertex> pointFactory, PMVMatrix pmvMatrix) {
        return new RenderState(pointFactory, pmvMatrix);
    }

    public static final RenderState getRenderState(GL2ES2 gl) {
        return (RenderState) gl.getContext().getAttachedObject(thisKey);
    }

    private final Vertex.Factory<? extends Vertex> vertexFactory;
    private final PMVMatrix pmvMatrix;
    private final float[] weight;
    private final FloatBuffer weightBuffer;
    private final float[] colorStatic;
    private final FloatBuffer colorStaticBuffer;
    private ShaderProgram sp;
    private int hintBitfield;

    private final int id;
    private static synchronized int getNextID() {
        return nextID++;
    }
    private static int nextID = 1;

    /**
     * Representation of {@link RenderState} data for one {@link ShaderProgram}
     * as {@link GLUniformData}.
     * <p>
     * FIXME: Utilize 'ARB_Uniform_Buffer_Object' where available!
     * </p>
     */
    public static class ProgramLocal {
        public final GLUniformData gcu_PMVMatrix01;
        public final GLUniformData gcu_Weight;
        public final GLUniformData gcu_ColorStatic;
        private int rsId = -1;

        public ProgramLocal() {
            gcu_PMVMatrix01 = GLUniformData.creatEmptyMatrix(UniformNames.gcu_PMVMatrix01, 4, 4);
            gcu_Weight = GLUniformData.creatEmptyVector(UniformNames.gcu_Weight, 1);
            gcu_ColorStatic = GLUniformData.creatEmptyVector(UniformNames.gcu_ColorStatic, 4);
        }

        public final int getRenderStateId() { return rsId; }

        /**
         * <p>
         * Since {@link RenderState} data is being used in multiple
         * {@link ShaderProgram}s the data must always be written.
         * </p>
         * @param gl
         * @param updateLocation
         * @param renderModes
         * @param throwOnError TODO
         * @return true if no error occurred, i.e. all locations found, otherwise false.
         */
        public final boolean update(final GL2ES2 gl, final RenderState rs, final boolean updateLocation, final int renderModes, final boolean pass1, final boolean throwOnError) {
            if( rs.id() != rsId ) {
                gcu_PMVMatrix01.setData(rs.pmvMatrix.glGetPMvMatrixf());
                gcu_Weight.setData(rs.weightBuffer);
                gcu_ColorStatic.setData(rs.colorStaticBuffer);
                rsId = rs.id();
            }
            boolean res = true;
            if( null != rs.sp && rs.sp.inUse() ) {
                if( !Region.isTwoPass(renderModes) || !pass1 ) {
                    final boolean r0 = rs.updateUniformDataLoc(gl, updateLocation, true, gcu_PMVMatrix01, throwOnError);
                    res = res && r0;
                }
                if( pass1 ) {
                    if( Region.hasVariableWeight( renderModes ) ) {
                        final boolean r0 = rs.updateUniformDataLoc(gl, updateLocation, true, gcu_Weight, throwOnError);
                        res = res && r0;
                    }
                    {
                        final boolean r0 = rs.updateUniformDataLoc(gl, updateLocation, true, gcu_ColorStatic, throwOnError);
                        res = res && r0;
                    }
                }
            }
            return res;
        }

        public StringBuilder toString(StringBuilder sb, boolean alsoUnlocated) {
            if(null==sb) {
                sb = new StringBuilder();
            }
            sb.append("ProgramLocal[rsID ").append(rsId).append(Platform.NEWLINE);
            // pmvMatrix.toString(sb, "%.2f");
            sb.append(gcu_PMVMatrix01).append(", ").append(Platform.NEWLINE);
            sb.append(gcu_ColorStatic).append(", ");
            sb.append(gcu_Weight).append("]");
            return sb;
        }

        @Override
        public String toString() {
            return toString(null, false).toString();
        }
    }

    protected RenderState(Vertex.Factory<? extends Vertex> vertexFactory, PMVMatrix pmvMatrix) {
        this.id = getNextID();
        this.sp = null;
        this.vertexFactory = vertexFactory;
        this.pmvMatrix = null != pmvMatrix ? pmvMatrix : new PMVMatrix();
        this.weight = new float[1];
        this.weightBuffer = FloatBuffer.wrap(weight);
        this.colorStatic = new float[4];
        this.colorStaticBuffer = FloatBuffer.wrap(colorStatic);
        this.hintBitfield = 0;
    }

    public final int id() { return id; }
    public final ShaderProgram getShaderProgram() { return sp; }
    public final boolean isShaderProgramInUse() { return null != sp ? sp.inUse() : false; }

    /**
     * Set a {@link ShaderProgram} and enable it. If the given {@link ShaderProgram} is new,
     * method returns true, otherwise false.
     * @param gl
     * @param spNext
     * @return true if a new shader program is being used and hence external uniform-data and -location,
     *         as well as the attribute-location must be updated, otherwise false.
     */
    public final boolean setShaderProgram(final GL2ES2 gl, final ShaderProgram spNext) {
        if( spNext.equals(this.sp) ) {
            spNext.useProgram(gl, true);
            return false;
        }
        if( null != this.sp ) {
            this.sp.notifyNotInUse();
        }
        this.sp = spNext;
        spNext.useProgram(gl, true);
        return true;
    }

    public final Vertex.Factory<? extends Vertex> getVertexFactory() { return vertexFactory; }

    public final PMVMatrix getMatrix() { return pmvMatrix; }

    public static boolean isWeightValid(float v) {
        return 0.0f <= v && v <= 1.9f ;
    }
    public final float getWeight() { return weight[0]; }
    public final void setWeight(float v) {
        if( !isWeightValid(v) ) {
             throw new IllegalArgumentException("Weight out of range");
        }
        weight[0] = v;
    }


    public final float[] getColorStatic(float[] rgbaColor) {
        System.arraycopy(colorStatic, 0, rgbaColor, 0, 4);
        return rgbaColor;
    }
    public final void setColorStatic(float r, float g, float b, float a){
        colorStatic[0] = r;
        colorStatic[1] = g;
        colorStatic[2] = b;
        colorStatic[3] = a;
    }


    /**
     *
     * @param gl
     * @param updateLocation
     * @param data
     * @param throwOnError TODO
     * @return true if no error occured, i.e. all locations found, otherwise false.
     */
    public final boolean updateUniformLoc(final GL2ES2 gl, final boolean updateLocation, final GLUniformData data, final boolean throwOnError) {
        if( updateLocation || 0 > data.getLocation() ) {
            final boolean ok = 0 <= data.setLocation(gl, sp.program());
            if( throwOnError && !ok ) {
                throw new GLException("Could not locate "+data);
            }
            return ok;
        } else {
            return true;
        }
    }

    /**
     *
     * @param gl
     * @param updateLocation
     * @param updateData TODO
     * @param data
     * @param throwOnError TODO
     * @return true if no error occured, i.e. all locations found, otherwise false.
     */
    public final boolean updateUniformDataLoc(final GL2ES2 gl, boolean updateLocation, boolean updateData, final GLUniformData data, final boolean throwOnError) {
        updateLocation = updateLocation || 0 > data.getLocation();
        if( updateLocation ) {
            updateData = 0 <= data.setLocation(gl, sp.program());
            if( throwOnError && !updateData ) {
                throw new GLException("Could not locate "+data);
            }
        }
        if( updateData ){
            gl.glUniform(data);
            return true;
        } else {
            return !updateLocation;
        }
    }

    /**
     * @param gl
     * @param data
     * @param throwOnError TODO
     * @return true if no error occured, i.e. all locations found, otherwise false.
     */
    public final boolean updateAttributeLoc(final GL2ES2 gl, final boolean updateLocation, final GLArrayDataServer data, boolean throwOnError) {
        if( updateLocation || 0 > data.getLocation() ) {
            final boolean ok = 0 <= data.setLocation(gl, sp.program());
            if( throwOnError && !ok ) {
                throw new GLException("Could not locate "+data);
            }
            return ok;
        } else {
            return true;
        }
    }


    public final boolean isHintMaskSet(int mask) {
        return mask == ( hintBitfield & mask );
    }
    public final void setHintMask(int mask) {
        hintBitfield |= mask;
    }
    public final void clearHintMask(int mask) {
        hintBitfield &= ~mask;
    }

    public void destroy(GL2ES2 gl) {
        if( null != sp ) {
            sp.destroy(gl);
            sp = null;
        }
    }

    public final RenderState attachTo(GL2ES2 gl) {
        return (RenderState) gl.getContext().attachObject(thisKey, this);
    }

    public final boolean detachFrom(GL2ES2 gl) {
        RenderState _rs = (RenderState) gl.getContext().getAttachedObject(thisKey);
        if(_rs == this) {
            gl.getContext().detachObject(thisKey);
            return true;
        }
        return false;
    }

    @Override
    public String toString() {
        return "RenderState["+sp+"]";
    }
}