Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedEffects.java @ 8e88389e

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
    int tfo = mesh.getTFO();
430

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

    
439
    mNormalProgram.useProgram();
440
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, mM.getMVP() , 0);
441
    mesh.bindTransformAttribs(mNormalProgram);
442
    GLES31.glLineWidth(8.0f);
443
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*num);
444
    }
445

    
446
///////////////////////////////////////////////////////////////////////////////////////////////////
447

    
448
  void send(float halfX, float halfY, float halfZ, float marginInPixels, DistortedOutputSurface surface, int variant)
449
    {
450
    float inflate=0.0f;
451

    
452
    mM.send(surface,halfX,halfY,halfZ,variant);
453

    
454
    if( marginInPixels!=0.0f )
455
      {
456
      inflate = mM.magnify(surface,halfX,halfY,halfZ,marginInPixels);
457
      }
458

    
459
    mV.send(inflate,variant);
460
    }
461

    
462
///////////////////////////////////////////////////////////////////////////////////////////////////
463

    
464
  void drawPrivOIT(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
465
    {
466
    float halfZ = halfW*mesh.getZFactor();
467

    
468
    mM.compute(currTime);
469
    mV.compute(currTime,halfW,halfH,halfZ);
470
    mF.compute(currTime,halfW,halfH);
471
    mP.compute(currTime);
472

    
473
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
474

    
475
    mMainOITProgram.useProgram();
476
    GLES31.glUniform1i(mMainOITTextureH, 0);
477
    GLES31.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
478
    GLES31.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
479

    
480
    mesh.bindVertexAttribs(mMainOITProgram);
481

    
482
    float inflate = mesh.getInflate();
483

    
484
    mM.send(surface,halfW,halfH,halfZ,1);
485
    mV.send(inflate,1);
486
    mF.send(1);
487

    
488
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
489

    
490
    if( mesh.getShowNormals() )
491
      {
492
      mMainProgram.useProgram();
493
      mM.send(surface,halfW,halfH,halfZ,0);
494
      mV.send(inflate,0);
495
      mF.send(0);
496
      displayNormals(mesh);
497
      }
498
    }
499

    
500
///////////////////////////////////////////////////////////////////////////////////////////////////
501

    
502
  void drawPriv(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
503
    {
504
    float halfZ = halfW*mesh.getZFactor();
505

    
506
    mM.compute(currTime);
507
    mV.compute(currTime,halfW,halfH,halfZ);
508
    mF.compute(currTime,halfW,halfH);
509
    mP.compute(currTime);
510

    
511
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
512

    
513
    mMainProgram.useProgram();
514
    GLES31.glUniform1i(mMainTextureH, 0);
515

    
516
    mesh.bindVertexAttribs(mMainProgram);
517

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

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

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

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

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

    
544
///////////////////////////////////////////////////////////////////////////////////////////////////
545

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

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

    
559
///////////////////////////////////////////////////////////////////////////////////////////////////
560

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

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

    
577
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
578

    
579
    return counter;
580
    }
581

    
582
///////////////////////////////////////////////////////////////////////////////////////////////////
583

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

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

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

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

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

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

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

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

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

    
633
    return counter;
634
    }
635

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

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

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

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

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

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

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

    
669
    mOITClearProgram.useProgram();
670

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

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

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

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

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

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

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

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

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

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

    
728
///////////////////////////////////////////////////////////////////////////////////////////////////
729

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

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

    
743
///////////////////////////////////////////////////////////////////////////////////////////////////
744

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

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

    
752
///////////////////////////////////////////////////////////////////////////////////////////////////
753

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

    
759
///////////////////////////////////////////////////////////////////////////////////////////////////
760

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

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

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

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

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

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

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

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

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

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

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

    
891
    return 0;
892
    }
893

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

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

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

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

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

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