Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedEffects.java @ 84d51487

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
  EffectQueueMatrix getMatrix()
409
    {
410
    return mM;
411
    }
412

    
413
///////////////////////////////////////////////////////////////////////////////////////////////////
414

    
415
  EffectQueueVertex getVertex()
416
    {
417
    return mV;
418
    }
419

    
420
///////////////////////////////////////////////////////////////////////////////////////////////////
421

    
422
  EffectQueueFragment getFragment()
423
    {
424
    return mF;
425
    }
426

    
427
///////////////////////////////////////////////////////////////////////////////////////////////////
428

    
429
  EffectQueuePostprocess getPostprocess()
430
    {
431
    return mP;
432
    }
433

    
434
///////////////////////////////////////////////////////////////////////////////////////////////////
435

    
436
  void newNode(DistortedNode node)
437
    {
438
    mP.newNode(node);
439
    }
440

    
441
///////////////////////////////////////////////////////////////////////////////////////////////////
442

    
443
  void removeNode(DistortedNode node)
444
    {
445
    mP.removeNode(node);
446
    }
447

    
448
///////////////////////////////////////////////////////////////////////////////////////////////////
449

    
450
  private void displayNormals(MeshBase mesh)
451
    {
452
    int num = mesh.getNumVertices();
453
    int tfo = mesh.getTFO();
454

    
455
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
456
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
457
    DistortedRenderState.switchOffDrawing();
458
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, num );
459
    DistortedRenderState.restoreDrawing();
460
    GLES31.glEndTransformFeedback();
461
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
462

    
463
    mNormalProgram.useProgram();
464
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, mM.getMVP() , 0);
465
    mesh.bindTransformAttribs(mNormalProgram);
466
    GLES31.glLineWidth(8.0f);
467
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*num);
468
    }
469

    
470
///////////////////////////////////////////////////////////////////////////////////////////////////
471

    
472
  void drawPrivOIT(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
473
    {
474
    float halfZ = halfW*mesh.getZFactor();
475

    
476
    mM.compute(currTime);
477
    mV.compute(currTime,halfW,halfH,halfZ);
478
    mF.compute(currTime,halfW,halfH,halfZ);
479
    mP.compute(currTime);
480

    
481
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
482

    
483
    mMainOITProgram.useProgram();
484
    GLES31.glUniform1i(mMainOITTextureH, 0);
485
    GLES31.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
486
    GLES31.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
487

    
488
    mesh.bindVertexAttribs(mMainOITProgram);
489

    
490
    float inflate = mesh.getInflate();
491

    
492
    mM.send(surface,halfW,halfH,halfZ,1);
493
    mV.send(inflate,1);
494
    mF.send(1);
495

    
496
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
497

    
498
    if( mesh.getShowNormals() )
499
      {
500
      mMainProgram.useProgram();
501
      mM.send(surface,halfW,halfH,halfZ,0);
502
      mV.send(inflate,0);
503
      mF.send(0);
504
      displayNormals(mesh);
505
      }
506
    }
507

    
508
///////////////////////////////////////////////////////////////////////////////////////////////////
509

    
510
  void drawPriv(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
511
    {
512
    float halfZ = halfW*mesh.getZFactor();
513

    
514
    mM.compute(currTime);
515
    mV.compute(currTime,halfW,halfH,halfZ);
516
    mF.compute(currTime,halfW,halfH,halfZ);
517
    mP.compute(currTime);
518

    
519
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
520

    
521
    mMainProgram.useProgram();
522
    GLES31.glUniform1i(mMainTextureH, 0);
523

    
524
    mesh.bindVertexAttribs(mMainProgram);
525

    
526
    mM.send(surface,halfW,halfH,halfZ,0);
527
    mV.send( mesh.getInflate(),0);
528
    mF.send(0);
529

    
530
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
531

    
532
    if( mesh.getShowNormals() ) displayNormals(mesh);
533
    }
534

    
535
///////////////////////////////////////////////////////////////////////////////////////////////////
536

    
537
  static void blitPriv(DistortedOutputSurface surface)
538
    {
539
    mBlitProgram.useProgram();
540

    
541
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
542
    GLES31.glUniform1i(mBlitTextureH, 0);
543
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
544
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
545
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
546
    }
547

    
548
///////////////////////////////////////////////////////////////////////////////////////////////////
549

    
550
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
551
    {
552
    mBlitDepthProgram.useProgram();
553

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

    
563
///////////////////////////////////////////////////////////////////////////////////////////////////
564

    
565
  private static int printPreviousBuffer()
566
    {
567
    int counter = 0;
568

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

    
581
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
582

    
583
    return counter;
584
    }
585

    
586
///////////////////////////////////////////////////////////////////////////////////////////////////
587

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

    
602
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
603
    }
604

    
605
///////////////////////////////////////////////////////////////////////////////////////////////////
606
// reset atomic counter to 0
607

    
608
  static int zeroOutAtomic()
609
    {
610
    int counter = 0;
611

    
612
    if( mAtomicCounter[0]<0 )
613
      {
614
      GLES31.glGenBuffers(Distorted.FBO_QUEUE_SIZE,mAtomicCounter,0);
615

    
616
      for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)
617
        {
618
        GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
619
        GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
620
        zeroBuffer();
621
        }
622
      }
623

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

    
632
    if( ++mCurrBuffer>=Distorted.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
633

    
634
    GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
635
    zeroBuffer();
636

    
637
    return counter;
638
    }
639

    
640
///////////////////////////////////////////////////////////////////////////////////////////////////
641
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
642

    
643
  static void oitClear(DistortedOutputSurface surface, int counter)
644
    {
645
    if( mLinkedListSSBO[0]<0 )
646
      {
647
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
648

    
649
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
650
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
651
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
652
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
653

    
654
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
655
      }
656

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

    
661
    if( overflow>1.0f )
662
      {
663
      //android.util.Log.e("effects", "previous frame rendered "+counter+
664
      //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
665

    
666
      mBufferSize *= (int)(overflow+1.0f);
667
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
668
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
669
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
670
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
671
      }
672

    
673
    mOITClearProgram.useProgram();
674

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

    
683
///////////////////////////////////////////////////////////////////////////////////////////////////
684
// Pass2 of the OIT algorithm - build per-pixel linked lists.
685

    
686
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
687
    {
688
    mOITBuildProgram.useProgram();
689

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

    
701
///////////////////////////////////////////////////////////////////////////////////////////////////
702
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
703

    
704
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
705
    {
706
    mOITCollapseProgram.useProgram();
707

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

    
717
///////////////////////////////////////////////////////////////////////////////////////////////////
718
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
719

    
720
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
721
    {
722
    mOITRenderProgram.useProgram();
723

    
724
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
725
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
726
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
727
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
728
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
729
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
730
    }
731

    
732
///////////////////////////////////////////////////////////////////////////////////////////////////
733

    
734
  private void releasePriv()
735
    {
736
    if( !matrixCloned      ) mM.abortAll(false);
737
    if( !vertexCloned      ) mV.abortAll(false);
738
    if( !fragmentCloned    ) mF.abortAll(false);
739
    if( !postprocessCloned ) mP.abortAll(false);
740

    
741
    mM = null;
742
    mV = null;
743
    mF = null;
744
    mP = null;
745
    }
746

    
747
///////////////////////////////////////////////////////////////////////////////////////////////////
748

    
749
  static void onPause()
750
    {
751
    mLinkedListSSBO[0]= -1;
752

    
753
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
754
    }
755

    
756
///////////////////////////////////////////////////////////////////////////////////////////////////
757

    
758
  static void onDestroy()
759
    {
760
    mNextID =  0;
761
    }
762

    
763
///////////////////////////////////////////////////////////////////////////////////////////////////
764

    
765
  static void setSSBOSize(float size)
766
    {
767
    mBufferSize = size;
768
    }
769

    
770
///////////////////////////////////////////////////////////////////////////////////////////////////
771
// PUBLIC API
772
///////////////////////////////////////////////////////////////////////////////////////////////////
773
/**
774
 * Create empty effect queue.
775
 */
776
  public DistortedEffects()
777
    {
778
    mID = ++mNextID;
779
    initializeEffectLists(this,0);
780
    }
781

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

    
798
///////////////////////////////////////////////////////////////////////////////////////////////////
799
/**
800
 * Releases all resources. After this call, the queue should not be used anymore.
801
 */
802
  @SuppressWarnings("unused")
803
  public synchronized void delete()
804
    {
805
    releasePriv();
806
    }
807

    
808
///////////////////////////////////////////////////////////////////////////////////////////////////
809
/**
810
 * Returns unique ID of this instance.
811
 *
812
 * @return ID of the object.
813
 */
814
  public long getID()
815
      {
816
      return mID;
817
      }
818

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

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

    
850
///////////////////////////////////////////////////////////////////////////////////////////////////
851
/**
852
 * Aborts all Effects.
853
 * @return Number of effects aborted.
854
 */
855
  public int abortAllEffects()
856
    {
857
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true) + mP.abortAll(true);
858
    }
859

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

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

    
890
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
891
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
892
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
893
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
894

    
895
    return 0;
896
    }
897

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

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

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

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

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

    
990
    return false;
991
    }
992
  }
(4-4/19)