Project

General

Profile

Download (38.3 KB) Statistics
| Branch: | Revision:

library / src / main / java / org / distorted / library / main / DistortedEffects.java @ 9a3607b3

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.library.main;
21

    
22
import android.content.res.Resources;
23
import android.opengl.GLES31;
24
import android.util.Log;
25

    
26
import org.distorted.library.R;
27
import org.distorted.library.effect.Effect;
28
import org.distorted.library.effect.EffectName;
29
import org.distorted.library.effect.EffectType;
30
import org.distorted.library.effect.FragmentEffect;
31
import org.distorted.library.effect.VertexEffect;
32
import org.distorted.library.mesh.MeshBase;
33
import org.distorted.library.message.EffectListener;
34
import org.distorted.library.program.DistortedProgram;
35

    
36
import java.io.InputStream;
37
import java.nio.ByteBuffer;
38
import java.nio.ByteOrder;
39
import java.nio.FloatBuffer;
40
import java.nio.IntBuffer;
41

    
42
///////////////////////////////////////////////////////////////////////////////////////////////////
43
/**
44
 * Class containing Matrix, Vertex, Fragment and Postprocessing effect queues.
45
 * <p>
46
 * The queues hold actual effects to be applied to a given (InputSurface,MeshBase) combo.
47
 */
48
public class DistortedEffects
49
  {
50
  /// MAIN PROGRAM ///
51
  private static DistortedProgram mMainProgram;
52
  private static int mMainTextureH;
53

    
54
  /// BLIT PROGRAM ///
55
  private static DistortedProgram mBlitProgram;
56
  private static int mBlitTextureH;
57
  private static int mBlitDepthH;
58
  private static final FloatBuffer mQuadPositions;
59

    
60
  static
61
    {
62
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
63
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
64
    mQuadPositions.put(positionData).position(0);
65
    }
66

    
67
  /// BLIT DEPTH PROGRAM ///
68
  private static DistortedProgram mBlitDepthProgram;
69
  private static int mBlitDepthTextureH;
70
  private static int mBlitDepthDepthTextureH;
71
  private static int mBlitDepthDepthH;
72
  private static int mBlitDepthTexCorrH;
73

    
74
  /// NORMAL PROGRAM /////
75
  private static DistortedProgram mNormalProgram;
76
  private static int mNormalMVPMatrixH;
77

    
78
  /// OIT SSBO BUFFER ///
79
  private static int[] mLinkedListSSBO = new int[1];
80
  private static int[] mAtomicCounter = new int[Distorted.FBO_QUEUE_SIZE];
81
  private static int   mCurrBuffer;
82

    
83
  static
84
    {
85
    mLinkedListSSBO[0]= -1;
86
    mCurrBuffer       =  0;
87

    
88
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)  mAtomicCounter[i] = -1;
89
    }
90

    
91
  ///////////////////////////////////////////////////////////////
92
  // meaning: allocate 1.0 screenful of places for transparent
93
  // fragments in the SSBO backing up the OIT render method.
94
  private static float mBufferSize=1.0f;
95

    
96
  /// OIT CLEAR PROGRAM ///
97
  private static DistortedProgram mOITClearProgram;
98
  private static int mOITClearDepthH;
99
  private static int mOITClearTexCorrH;
100
  private static int mOITClearSizeH;
101

    
102
  /// OIT BUILD PROGRAM ///
103
  private static DistortedProgram mOITBuildProgram;
104
  private static int mOITBuildTextureH;
105
  private static int mOITBuildDepthTextureH;
106
  private static int mOITBuildDepthH;
107
  private static int mOITBuildTexCorrH;
108
  private static int mOITBuildSizeH;
109
  private static int mOITBuildNumRecordsH;
110

    
111
  /// OIT COLLAPSE PROGRAM ///
112
  private static DistortedProgram mOITCollapseProgram;
113
  private static int mOITCollapseDepthTextureH;
114
  private static int mOITCollapseDepthH;
115
  private static int mOITCollapseTexCorrH;
116
  private static int mOITCollapseSizeH;
117

    
118
  /// OIT RENDER PROGRAM ///
119
  private static DistortedProgram mOITRenderProgram;
120
  private static int mOITRenderDepthH;
121
  private static int mOITRenderTexCorrH;
122
  private static int mOITRenderSizeH;
123

    
124
  /// MAIN OIT PROGRAM ///
125
  private static DistortedProgram mMainOITProgram;
126
  private static int mMainOITTextureH;
127
  private static int mMainOITSizeH;
128
  private static int mMainOITNumRecordsH;
129
  /// END PROGRAMS //////
130

    
131
  private static long mNextID =0;
132
  private long mID;
133

    
134
  private EffectQueueMatrix mM;
135
  private EffectQueueFragment mF;
136
  private EffectQueueVertex mV;
137
  private EffectQueuePostprocess mP;
138

    
139
  private boolean matrixCloned, vertexCloned, fragmentCloned, postprocessCloned;
140

    
141
///////////////////////////////////////////////////////////////////////////////////////////////////
142

    
143
  static void createPrograms(Resources resources)
144
    {
145
    // MAIN PROGRAM ////////////////////////////////////
146
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
147
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
148

    
149
    int numF = FragmentEffect.getNumEnabled();
150
    int numV = VertexEffect.getNumEnabled();
151

    
152
    String mainVertHeader= Distorted.GLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
153
    String mainFragHeader= Distorted.GLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
154
    String enabledEffectV= VertexEffect.getGLSL();
155
    String enabledEffectF= FragmentEffect.getGLSL();
156

    
157
    //android.util.Log.e("Effects", "vertHeader= "+mainVertHeader);
158
    //android.util.Log.e("Effects", "fragHeader= "+mainFragHeader);
159
    //android.util.Log.e("Effects", "enabledV= "+enabledEffectV);
160
    //android.util.Log.e("Effects", "enabledF= "+enabledEffectF);
161

    
162
    String[] feedback = { "v_Position", "v_endPosition" };
163

    
164
    try
165
      {
166
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
167
                                          enabledEffectV, enabledEffectF, Distorted.GLSL, feedback);
168
      }
169
    catch(Exception e)
170
      {
171
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
172
      throw new RuntimeException(e.getMessage());
173
      }
174

    
175
    int mainProgramH = mMainProgram.getProgramHandle();
176
    EffectQueueFragment.getUniforms(mainProgramH,0);
177
    EffectQueueVertex.getUniforms(mainProgramH,0);
178
    EffectQueueMatrix.getUniforms(mainProgramH,0);
179
    mMainTextureH= GLES31.glGetUniformLocation( mainProgramH, "u_Texture");
180

    
181
    // BLIT PROGRAM ////////////////////////////////////
182
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
183
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
184

    
185
    try
186
      {
187
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
188
      }
189
    catch(Exception e)
190
      {
191
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
192
      throw new RuntimeException(e.getMessage());
193
      }
194

    
195
    int blitProgramH = mBlitProgram.getProgramHandle();
196
    mBlitTextureH  = GLES31.glGetUniformLocation( blitProgramH, "u_Texture");
197
    mBlitDepthH    = GLES31.glGetUniformLocation( blitProgramH, "u_Depth");
198

    
199
    // BLIT DEPTH PROGRAM ////////////////////////////////////
200
    final InputStream blitDepthVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
201
    final InputStream blitDepthFragStream = resources.openRawResource(R.raw.blit_depth_fragment_shader);
202

    
203
    try
204
      {
205
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
206
      }
207
    catch(Exception e)
208
      {
209
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
210
      throw new RuntimeException(e.getMessage());
211
      }
212

    
213
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
214
    mBlitDepthTextureH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Texture");
215
    mBlitDepthDepthTextureH = GLES31.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
216
    mBlitDepthDepthH        = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Depth");
217
    mBlitDepthTexCorrH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
218

    
219
    // NORMAL PROGRAM //////////////////////////////////////
220
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
221
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
222

    
223
    try
224
      {
225
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, Distorted.GLSL_VERSION, Distorted.GLSL_VERSION, Distorted.GLSL);
226
      }
227
    catch(Exception e)
228
      {
229
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
230
      throw new RuntimeException(e.getMessage());
231
      }
232

    
233
    int normalProgramH = mNormalProgram.getProgramHandle();
234
    mNormalMVPMatrixH  = GLES31.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
235
    }
236

    
237
///////////////////////////////////////////////////////////////////////////////////////////////////
238

    
239
  static void createProgramsOIT(Resources resources)
240
    {
241
    // MAIN OIT PROGRAM ////////////////////////////////
242
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
243
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
244

    
245
    int numF = FragmentEffect.getNumEnabled();
246
    int numV = VertexEffect.getNumEnabled();
247

    
248
    String mainVertHeader= Distorted.GLSL_VERSION +
249
                           ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") +
250
                           ("#define OIT\n");
251
    String mainFragHeader= Distorted.GLSL_VERSION +
252
                           ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") +
253
                           ("#define OIT\n");
254

    
255
    String enabledEffectV= VertexEffect.getGLSL();
256
    String enabledEffectF= FragmentEffect.getGLSL();
257

    
258
    try
259
      {
260
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
261
                                             enabledEffectV, enabledEffectF, Distorted.GLSL, null);
262
      }
263
    catch(Exception e)
264
      {
265
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
266
      throw new RuntimeException(e.getMessage());
267
      }
268

    
269
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
270
    EffectQueueFragment.getUniforms(mainOITProgramH,1);
271
    EffectQueueVertex.getUniforms(mainOITProgramH,1);
272
    EffectQueueMatrix.getUniforms(mainOITProgramH,1);
273
    mMainOITTextureH    = GLES31.glGetUniformLocation( mainOITProgramH, "u_Texture");
274
    mMainOITSizeH       = GLES31.glGetUniformLocation( mainOITProgramH, "u_Size");
275
    mMainOITNumRecordsH = GLES31.glGetUniformLocation( mainOITProgramH, "u_numRecords");
276

    
277
    // OIT CLEAR PROGRAM ////////////////////////////////////
278
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
279
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
280

    
281
    try
282
      {
283
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
284
      }
285
    catch(Exception e)
286
      {
287
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
288
      throw new RuntimeException(e.getMessage());
289
      }
290

    
291
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
292
    mOITClearDepthH        = GLES31.glGetUniformLocation( oitClearProgramH, "u_Depth");
293
    mOITClearTexCorrH      = GLES31.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
294
    mOITClearSizeH         = GLES31.glGetUniformLocation( oitClearProgramH, "u_Size");
295

    
296
    // OIT BUILD PROGRAM ////////////////////////////////////
297
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
298
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
299

    
300
    try
301
      {
302
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
303
      }
304
    catch(Exception e)
305
      {
306
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
307
      throw new RuntimeException(e.getMessage());
308
      }
309

    
310
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
311
    mOITBuildTextureH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Texture");
312
    mOITBuildDepthTextureH = GLES31.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
313
    mOITBuildDepthH        = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Depth");
314
    mOITBuildTexCorrH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
315
    mOITBuildSizeH         = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Size");
316
    mOITBuildNumRecordsH   = GLES31.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
317

    
318
    // OIT COLLAPSE PROGRAM ///////////////////////////
319
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
320
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
321

    
322
    try
323
      {
324
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
325
      }
326
    catch(Exception e)
327
      {
328
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
329
      throw new RuntimeException(e.getMessage());
330
      }
331

    
332
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
333
    mOITCollapseDepthTextureH = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
334
    mOITCollapseDepthH        = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
335
    mOITCollapseTexCorrH      = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
336
    mOITCollapseSizeH         = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Size");
337

    
338
    // OIT RENDER PROGRAM ///////////////////////////
339
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
340
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
341

    
342
    try
343
      {
344
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
345
      }
346
    catch(Exception e)
347
      {
348
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
349
      throw new RuntimeException(e.getMessage());
350
      }
351

    
352
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
353
    mOITRenderDepthH        = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Depth");
354
    mOITRenderTexCorrH      = GLES31.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
355
    mOITRenderSizeH         = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Size");
356
    }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359

    
360
  private void initializeEffectLists(DistortedEffects d, int flags)
361
    {
362
    if( (flags & Distorted.CLONE_MATRIX) != 0 )
363
      {
364
      mM = d.mM;
365
      matrixCloned = true;
366
      }
367
    else
368
      {
369
      mM = new EffectQueueMatrix(mID);
370
      matrixCloned = false;
371
      }
372
    
373
    if( (flags & Distorted.CLONE_VERTEX) != 0 )
374
      {
375
      mV = d.mV;
376
      vertexCloned = true;
377
      }
378
    else
379
      {
380
      mV = new EffectQueueVertex(mID);
381
      vertexCloned = false;
382
      }
383
    
384
    if( (flags & Distorted.CLONE_FRAGMENT) != 0 )
385
      {
386
      mF = d.mF;
387
      fragmentCloned = true;
388
      }
389
    else
390
      {
391
      mF = new EffectQueueFragment(mID);
392
      fragmentCloned = false;
393
      }
394

    
395
    if( (flags & Distorted.CLONE_POSTPROCESS) != 0 )
396
      {
397
      mP = d.mP;
398
      postprocessCloned = true;
399
      }
400
    else
401
      {
402
      mP = new EffectQueuePostprocess(mID);
403
      postprocessCloned = false;
404
      }
405
    }
406

    
407
///////////////////////////////////////////////////////////////////////////////////////////////////
408

    
409
  EffectQueuePostprocess getPostprocess()
410
    {
411
    return mP;
412
    }
413

    
414
///////////////////////////////////////////////////////////////////////////////////////////////////
415

    
416
  void newNode(DistortedNode node)
417
    {
418
    mM.newNode(node);
419
    mF.newNode(node);
420
    mV.newNode(node);
421
    mP.newNode(node);
422
    }
423

    
424
///////////////////////////////////////////////////////////////////////////////////////////////////
425

    
426
  private void displayNormals(MeshBase mesh)
427
    {
428
    int num = mesh.getNumVertices();
429

    
430
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, mesh.getTFO() );
431
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
432
    DistortedRenderState.switchOffDrawing();
433
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, num );
434
    DistortedRenderState.restoreDrawing();
435
    GLES31.glEndTransformFeedback();
436
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
437

    
438
    mNormalProgram.useProgram();
439
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, mM.getMVP() , 0);
440
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.getTFO() );
441
    GLES31.glVertexAttribPointer(mNormalProgram.mAttribute[0], MeshBase.POS_DATA_SIZE, GLES31.GL_FLOAT, false, 0, 0);
442
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
443
    GLES31.glLineWidth(8.0f);
444
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*num);
445
    }
446

    
447
///////////////////////////////////////////////////////////////////////////////////////////////////
448

    
449
  void send(float halfW, float halfH, float halfZ, float margin, DistortedOutputSurface surface, int variant)
450
    {
451
    mM.send(surface,halfW,halfH,halfZ,margin,variant);
452
    mV.send(variant);
453
    }
454

    
455
///////////////////////////////////////////////////////////////////////////////////////////////////
456

    
457
  void drawPrivOIT(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
458
    {
459
    float halfZ = halfW*mesh.getZFactor();
460

    
461
    mM.compute(currTime);
462
    mV.compute(currTime,halfW,halfH,halfZ);
463
    mF.compute(currTime,halfW,halfH);
464
    mP.compute(currTime);
465

    
466
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
467

    
468
    mMainOITProgram.useProgram();
469
    GLES31.glUniform1i(mMainOITTextureH, 0);
470
    GLES31.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
471
    GLES31.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
472

    
473
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.getVBO() );
474
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[0], MeshBase.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshBase.VERTSIZE, MeshBase.OFFSET0);
475
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[1], MeshBase.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshBase.VERTSIZE, MeshBase.OFFSET1);
476
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[2], MeshBase.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshBase.VERTSIZE, MeshBase.OFFSET2);
477
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
478

    
479
    mM.send(surface,halfW,halfH,halfZ,0,1);
480
    mV.send(1);
481
    mF.send(1);
482

    
483
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
484

    
485
    if( mesh.getShowNormals() )
486
      {
487
      mMainProgram.useProgram();
488
      mM.send(surface,halfW,halfH,halfZ,0,0);
489
      mV.send(0);
490
      mF.send(0);
491
      displayNormals(mesh);
492
      }
493
    }
494

    
495
///////////////////////////////////////////////////////////////////////////////////////////////////
496

    
497
  void drawPriv(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
498
    {
499
    float halfZ = halfW*mesh.getZFactor();
500

    
501
    mM.compute(currTime);
502
    mV.compute(currTime,halfW,halfH,halfZ);
503
    mF.compute(currTime,halfW,halfH);
504
    mP.compute(currTime);
505

    
506
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
507

    
508
    mMainProgram.useProgram();
509
    GLES31.glUniform1i(mMainTextureH, 0);
510

    
511
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.getVBO() );
512
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshBase.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshBase.VERTSIZE, MeshBase.OFFSET0);
513
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshBase.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshBase.VERTSIZE, MeshBase.OFFSET1);
514
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshBase.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshBase.VERTSIZE, MeshBase.OFFSET2);
515
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
516

    
517
    mM.send(surface,halfW,halfH,halfZ,0,0);
518
    mV.send(0);
519
    mF.send(0);
520

    
521
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
522

    
523
    if( mesh.getShowNormals() ) displayNormals(mesh);
524
    }
525

    
526
///////////////////////////////////////////////////////////////////////////////////////////////////
527
/**
528
 * Only for use by the library itself.
529
 *
530
 * @y.exclude
531
 */
532
  public static void blitPriv(DistortedOutputSurface surface)
533
    {
534
    mBlitProgram.useProgram();
535

    
536
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
537
    GLES31.glUniform1i(mBlitTextureH, 0);
538
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
539
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
540
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
541
    }
542

    
543
///////////////////////////////////////////////////////////////////////////////////////////////////
544

    
545
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
546
    {
547
    mBlitDepthProgram.useProgram();
548

    
549
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
550
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
551
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
552
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
553
    GLES31.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
554
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
555
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
556
    }
557

    
558
///////////////////////////////////////////////////////////////////////////////////////////////////
559

    
560
  private static int printPreviousBuffer()
561
    {
562
    int counter = 0;
563

    
564
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
565
                                                                GLES31.GL_MAP_READ_BIT);
566
    if( atomicBuf!=null )
567
      {
568
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
569
      counter = atomicIntBuf.get(0);
570
      }
571
    else
572
      {
573
      android.util.Log.e("effects", "print: failed to map atomic buffer");
574
      }
575

    
576
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
577

    
578
    return counter;
579
    }
580

    
581
///////////////////////////////////////////////////////////////////////////////////////////////////
582

    
583
  private static void zeroBuffer()
584
    {
585
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
586
        GLES31.GL_MAP_WRITE_BIT|GLES31.GL_MAP_INVALIDATE_BUFFER_BIT);
587
    if( atomicBuf!=null )
588
      {
589
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
590
      atomicIntBuf.put(0,0);
591
      }
592
    else
593
      {
594
      android.util.Log.e("effects", "zero: failed to map atomic buffer");
595
      }
596

    
597
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
598
    }
599

    
600
///////////////////////////////////////////////////////////////////////////////////////////////////
601
// reset atomic counter to 0
602

    
603
  static int zeroOutAtomic()
604
    {
605
    int counter = 0;
606

    
607
    if( mAtomicCounter[0]<0 )
608
      {
609
      GLES31.glGenBuffers(Distorted.FBO_QUEUE_SIZE,mAtomicCounter,0);
610

    
611
      for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)
612
        {
613
        GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
614
        GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
615
        zeroBuffer();
616
        }
617
      }
618

    
619
    // reading the value of the buffer on every frame would slow down rendering by
620
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
621
    if( mCurrBuffer==0 )
622
      {
623
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
624
      counter = printPreviousBuffer();
625
      }
626

    
627
    if( ++mCurrBuffer>=Distorted.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
628

    
629
    GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
630
    zeroBuffer();
631

    
632
    return counter;
633
    }
634

    
635
///////////////////////////////////////////////////////////////////////////////////////////////////
636
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
637

    
638
  static void oitClear(DistortedOutputSurface surface, int counter)
639
    {
640
    if( mLinkedListSSBO[0]<0 )
641
      {
642
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
643

    
644
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
645
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
646
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
647
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
648

    
649
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
650
      }
651

    
652
    // See if we have overflown the SSBO in one of the previous frames.
653
    // If yes, assume we need to make the SSBO larger.
654
    float overflow = counter/(mBufferSize*surface.mWidth*surface.mHeight);
655

    
656
    if( overflow>1.0f )
657
      {
658
      //android.util.Log.e("effects", "previous frame rendered "+counter+
659
      //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
660

    
661
      mBufferSize *= (int)(overflow+1.0f);
662
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
663
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
664
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
665
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
666
      }
667

    
668
    mOITClearProgram.useProgram();
669

    
670
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
671
    GLES31.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
672
    GLES31.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
673
    GLES31.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
674
    GLES31.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
675
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
676
    }
677

    
678
///////////////////////////////////////////////////////////////////////////////////////////////////
679
// Pass2 of the OIT algorithm - build per-pixel linked lists.
680

    
681
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
682
    {
683
    mOITBuildProgram.useProgram();
684

    
685
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
686
    GLES31.glUniform1i(mOITBuildTextureH, 0);
687
    GLES31.glUniform1i(mOITBuildDepthTextureH, 1);
688
    GLES31.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
689
    GLES31.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
690
    GLES31.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
691
    GLES31.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
692
    GLES31.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
693
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
694
    }
695

    
696
///////////////////////////////////////////////////////////////////////////////////////////////////
697
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
698

    
699
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
700
    {
701
    mOITCollapseProgram.useProgram();
702

    
703
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
704
    GLES31.glUniform1i(mOITCollapseDepthTextureH, 1);
705
    GLES31.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
706
    GLES31.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
707
    GLES31.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
708
    GLES31.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
709
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
710
    }
711

    
712
///////////////////////////////////////////////////////////////////////////////////////////////////
713
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
714

    
715
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
716
    {
717
    mOITRenderProgram.useProgram();
718

    
719
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
720
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
721
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
722
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
723
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
724
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
725
    }
726

    
727
///////////////////////////////////////////////////////////////////////////////////////////////////
728

    
729
  private void releasePriv()
730
    {
731
    if( !matrixCloned      ) mM.abortAll(false);
732
    if( !vertexCloned      ) mV.abortAll(false);
733
    if( !fragmentCloned    ) mF.abortAll(false);
734
    if( !postprocessCloned ) mP.abortAll(false);
735

    
736
    mM = null;
737
    mV = null;
738
    mF = null;
739
    mP = null;
740
    }
741

    
742
///////////////////////////////////////////////////////////////////////////////////////////////////
743

    
744
  static void onPause()
745
    {
746
    mLinkedListSSBO[0]= -1;
747

    
748
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
749
    }
750

    
751
///////////////////////////////////////////////////////////////////////////////////////////////////
752

    
753
  static void onDestroy()
754
    {
755
    mNextID =  0;
756
    }
757

    
758
///////////////////////////////////////////////////////////////////////////////////////////////////
759

    
760
  static void setSSBOSize(float size)
761
    {
762
    mBufferSize = size;
763
    }
764

    
765
///////////////////////////////////////////////////////////////////////////////////////////////////
766
// PUBLIC API
767
///////////////////////////////////////////////////////////////////////////////////////////////////
768
/**
769
 * Create empty effect queue.
770
 */
771
  public DistortedEffects()
772
    {
773
    mID = ++mNextID;
774
    initializeEffectLists(this,0);
775
    }
776

    
777
///////////////////////////////////////////////////////////////////////////////////////////////////
778
/**
779
 * Copy constructor.
780
 * <p>
781
 * Whatever we do not clone gets created just like in the default constructor.
782
 *
783
 * @param dc    Source object to create our object from
784
 * @param flags A bitmask of values specifying what to copy.
785
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
786
 */
787
  public DistortedEffects(DistortedEffects dc, int flags)
788
    {
789
    mID = ++mNextID;
790
    initializeEffectLists(dc,flags);
791
    }
792

    
793
///////////////////////////////////////////////////////////////////////////////////////////////////
794
/**
795
 * Releases all resources. After this call, the queue should not be used anymore.
796
 */
797
  @SuppressWarnings("unused")
798
  public synchronized void delete()
799
    {
800
    releasePriv();
801
    }
802

    
803
///////////////////////////////////////////////////////////////////////////////////////////////////
804
/**
805
 * Returns unique ID of this instance.
806
 *
807
 * @return ID of the object.
808
 */
809
  public long getID()
810
      {
811
      return mID;
812
      }
813

    
814
///////////////////////////////////////////////////////////////////////////////////////////////////
815
/**
816
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
817
 * to one of the Effects in our queues. Nothing will happen if 'el' is already in the list.
818
 * 
819
 * @param el A class implementing the EffectListener interface that wants to get notifications.
820
 */
821
  @SuppressWarnings("unused")
822
  public void registerForMessages(EffectListener el)
823
    {
824
    mM.registerForMessages(el);
825
    mV.registerForMessages(el);
826
    mF.registerForMessages(el);
827
    mP.registerForMessages(el);
828
    }
829

    
830
///////////////////////////////////////////////////////////////////////////////////////////////////
831
/**
832
 * Removes the calling class from the list of Listeners that get notified if something happens to Effects in our queue.
833
 * 
834
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
835
 */
836
  @SuppressWarnings("unused")
837
  public void deregisterForMessages(EffectListener el)
838
    {
839
    mM.deregisterForMessages(el);
840
    mV.deregisterForMessages(el);
841
    mF.deregisterForMessages(el);
842
    mP.deregisterForMessages(el);
843
    }
844

    
845
///////////////////////////////////////////////////////////////////////////////////////////////////
846
/**
847
 * Aborts all Effects.
848
 * @return Number of effects aborted.
849
 */
850
  public int abortAllEffects()
851
    {
852
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
853
    }
854

    
855
///////////////////////////////////////////////////////////////////////////////////////////////////
856
/**
857
 * Aborts all Effects of a given type, for example all MATRIX Effects.
858
 * 
859
 * @param type one of the constants defined in {@link EffectType}
860
 * @return Number of effects aborted.
861
 */
862
  public int abortByType(EffectType type)
863
    {
864
    switch(type)
865
      {
866
      case MATRIX     : return mM.abortAll(true);
867
      case VERTEX     : return mV.abortAll(true);
868
      case FRAGMENT   : return mF.abortAll(true);
869
      case POSTPROCESS: return mP.abortAll(true);
870
      default         : return 0;
871
      }
872
    }
873

    
874
///////////////////////////////////////////////////////////////////////////////////////////////////
875
/**
876
 * Aborts an Effect by its ID.
877
 *
878
 * @param id the Id of the Effect to be removed, as returned by getID().
879
 * @return Number of effects aborted.
880
 */
881
  public int abortById(long id)
882
    {
883
    long type = id&EffectType.MASK;
884

    
885
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
886
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
887
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
888
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
889

    
890
    return 0;
891
    }
892

    
893
///////////////////////////////////////////////////////////////////////////////////////////////////
894
/**
895
 * Aborts a single Effect.
896
 * 
897
 * @param effect the Effect we want to abort.
898
 * @return number of Effects aborted. Always either 0 or 1.
899
 */
900
  public int abortEffect(Effect effect)
901
    {
902
    switch(effect.getType())
903
      {
904
      case MATRIX     : return mM.removeEffect(effect);
905
      case VERTEX     : return mV.removeEffect(effect);
906
      case FRAGMENT   : return mF.removeEffect(effect);
907
      case POSTPROCESS: return mP.removeEffect(effect);
908
      default         : return 0;
909
      }
910
    }
911

    
912
///////////////////////////////////////////////////////////////////////////////////////////////////
913
/**
914
 * Abort all Effects of a given name, for example all rotations.
915
 * 
916
 * @param name one of the constants defined in {@link EffectName}
917
 * @return number of Effects aborted.
918
 */
919
  public int abortByName(EffectName name)
920
    {
921
    switch(name.getType())
922
      {
923
      case MATRIX     : return mM.removeByName(name);
924
      case VERTEX     : return mV.removeByName(name);
925
      case FRAGMENT   : return mF.removeByName(name);
926
      case POSTPROCESS: return mP.removeByName(name);
927
      default                : return 0;
928
      }
929
    }
930

    
931
///////////////////////////////////////////////////////////////////////////////////////////////////
932
/**
933
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
934
 * single (InputSurface,MeshBase) combo.
935
 *
936
 * @param type {@link EffectType}
937
 * @return The maximum number of effects of a given type.
938
 */
939
  @SuppressWarnings("unused")
940
  public static int getMax(EffectType type)
941
    {
942
    return EffectQueue.getMax(type.ordinal());
943
    }
944

    
945
///////////////////////////////////////////////////////////////////////////////////////////////////
946
/**
947
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
948
 * This can fail if:
949
 * <ul>
950
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
951
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
952
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
953
 *     time only decreasing the value of 'max' is permitted.
954
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
955
 * </ul>
956
 *
957
 * @param type {@link EffectType}
958
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
959
 *            than Byte.MAX_VALUE
960
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
961
 */
962
  @SuppressWarnings("unused")
963
  public static boolean setMax(EffectType type, int max)
964
    {
965
    return EffectQueue.setMax(type.ordinal(),max);
966
    }
967

    
968
///////////////////////////////////////////////////////////////////////////////////////////////////
969
/**
970
 * Add a new Effect to our queue.
971
 *
972
 * @param effect The Effect to add.
973
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
974
 */
975
  public boolean apply(Effect effect)
976
    {
977
    switch(effect.getType())
978
      {
979
      case MATRIX      : return mM.add(effect);
980
      case VERTEX      : return mV.add(effect);
981
      case FRAGMENT    : return mF.add(effect);
982
      case POSTPROCESS : return mP.add(effect);
983
      }
984

    
985
    return false;
986
    }
987
  }
(3-3/17)