Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedEffects.java @ 15290f35

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 halfW, float halfH, float halfZ, float inflate, DistortedOutputSurface surface, int variant)
449
    {
450
    mM.send(surface,halfW,halfH,halfZ,variant);
451
    mV.send(inflate,variant);
452
    }
453

    
454
///////////////////////////////////////////////////////////////////////////////////////////////////
455

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

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

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

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

    
472
    mesh.bindVertexAttribs(mMainOITProgram);
473

    
474
    float inflate = mesh.getInflate();
475

    
476
    mM.send(surface,halfW,halfH,halfZ,1);
477
    mV.send(inflate,1);
478
    mF.send(1);
479

    
480
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
481

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

    
492
///////////////////////////////////////////////////////////////////////////////////////////////////
493

    
494
  void drawPriv(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
495
    {
496
    float halfZ = halfW*mesh.getZFactor();
497

    
498
    mM.compute(currTime);
499
    mV.compute(currTime,halfW,halfH,halfZ);
500
    mF.compute(currTime,halfW,halfH);
501
    mP.compute(currTime);
502

    
503
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
504

    
505
    mMainProgram.useProgram();
506
    GLES31.glUniform1i(mMainTextureH, 0);
507

    
508
    mesh.bindVertexAttribs(mMainProgram);
509

    
510
    mM.send(surface,halfW,halfH,halfZ,0);
511
    mV.send( mesh.getInflate(),0);
512
    mF.send(0);
513

    
514
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
515

    
516
    if( mesh.getShowNormals() ) displayNormals(mesh);
517
    }
518

    
519
///////////////////////////////////////////////////////////////////////////////////////////////////
520
/**
521
 * Only for use by the library itself.
522
 *
523
 * @y.exclude
524
 */
525
  public static void blitPriv(DistortedOutputSurface surface)
526
    {
527
    mBlitProgram.useProgram();
528

    
529
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
530
    GLES31.glUniform1i(mBlitTextureH, 0);
531
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
532
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
533
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
534
    }
535

    
536
///////////////////////////////////////////////////////////////////////////////////////////////////
537

    
538
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
539
    {
540
    mBlitDepthProgram.useProgram();
541

    
542
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
543
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
544
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
545
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
546
    GLES31.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
547
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
548
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
549
    }
550

    
551
///////////////////////////////////////////////////////////////////////////////////////////////////
552

    
553
  private static int printPreviousBuffer()
554
    {
555
    int counter = 0;
556

    
557
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
558
                                                                GLES31.GL_MAP_READ_BIT);
559
    if( atomicBuf!=null )
560
      {
561
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
562
      counter = atomicIntBuf.get(0);
563
      }
564
    else
565
      {
566
      android.util.Log.e("effects", "print: failed to map atomic buffer");
567
      }
568

    
569
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
570

    
571
    return counter;
572
    }
573

    
574
///////////////////////////////////////////////////////////////////////////////////////////////////
575

    
576
  private static void zeroBuffer()
577
    {
578
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
579
        GLES31.GL_MAP_WRITE_BIT|GLES31.GL_MAP_INVALIDATE_BUFFER_BIT);
580
    if( atomicBuf!=null )
581
      {
582
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
583
      atomicIntBuf.put(0,0);
584
      }
585
    else
586
      {
587
      android.util.Log.e("effects", "zero: failed to map atomic buffer");
588
      }
589

    
590
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
591
    }
592

    
593
///////////////////////////////////////////////////////////////////////////////////////////////////
594
// reset atomic counter to 0
595

    
596
  static int zeroOutAtomic()
597
    {
598
    int counter = 0;
599

    
600
    if( mAtomicCounter[0]<0 )
601
      {
602
      GLES31.glGenBuffers(Distorted.FBO_QUEUE_SIZE,mAtomicCounter,0);
603

    
604
      for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)
605
        {
606
        GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
607
        GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
608
        zeroBuffer();
609
        }
610
      }
611

    
612
    // reading the value of the buffer on every frame would slow down rendering by
613
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
614
    if( mCurrBuffer==0 )
615
      {
616
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
617
      counter = printPreviousBuffer();
618
      }
619

    
620
    if( ++mCurrBuffer>=Distorted.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
621

    
622
    GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
623
    zeroBuffer();
624

    
625
    return counter;
626
    }
627

    
628
///////////////////////////////////////////////////////////////////////////////////////////////////
629
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
630

    
631
  static void oitClear(DistortedOutputSurface surface, int counter)
632
    {
633
    if( mLinkedListSSBO[0]<0 )
634
      {
635
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
636

    
637
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
638
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
639
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
640
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
641

    
642
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
643
      }
644

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

    
649
    if( overflow>1.0f )
650
      {
651
      //android.util.Log.e("effects", "previous frame rendered "+counter+
652
      //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
653

    
654
      mBufferSize *= (int)(overflow+1.0f);
655
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
656
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
657
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
658
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
659
      }
660

    
661
    mOITClearProgram.useProgram();
662

    
663
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
664
    GLES31.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
665
    GLES31.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
666
    GLES31.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
667
    GLES31.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
668
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
669
    }
670

    
671
///////////////////////////////////////////////////////////////////////////////////////////////////
672
// Pass2 of the OIT algorithm - build per-pixel linked lists.
673

    
674
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
675
    {
676
    mOITBuildProgram.useProgram();
677

    
678
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
679
    GLES31.glUniform1i(mOITBuildTextureH, 0);
680
    GLES31.glUniform1i(mOITBuildDepthTextureH, 1);
681
    GLES31.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
682
    GLES31.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
683
    GLES31.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
684
    GLES31.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
685
    GLES31.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
686
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
687
    }
688

    
689
///////////////////////////////////////////////////////////////////////////////////////////////////
690
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
691

    
692
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
693
    {
694
    mOITCollapseProgram.useProgram();
695

    
696
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
697
    GLES31.glUniform1i(mOITCollapseDepthTextureH, 1);
698
    GLES31.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
699
    GLES31.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
700
    GLES31.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
701
    GLES31.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
702
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
703
    }
704

    
705
///////////////////////////////////////////////////////////////////////////////////////////////////
706
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
707

    
708
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
709
    {
710
    mOITRenderProgram.useProgram();
711

    
712
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
713
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
714
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
715
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
716
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
717
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
718
    }
719

    
720
///////////////////////////////////////////////////////////////////////////////////////////////////
721

    
722
  private void releasePriv()
723
    {
724
    if( !matrixCloned      ) mM.abortAll(false);
725
    if( !vertexCloned      ) mV.abortAll(false);
726
    if( !fragmentCloned    ) mF.abortAll(false);
727
    if( !postprocessCloned ) mP.abortAll(false);
728

    
729
    mM = null;
730
    mV = null;
731
    mF = null;
732
    mP = null;
733
    }
734

    
735
///////////////////////////////////////////////////////////////////////////////////////////////////
736

    
737
  static void onPause()
738
    {
739
    mLinkedListSSBO[0]= -1;
740

    
741
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
742
    }
743

    
744
///////////////////////////////////////////////////////////////////////////////////////////////////
745

    
746
  static void onDestroy()
747
    {
748
    mNextID =  0;
749
    }
750

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

    
753
  static void setSSBOSize(float size)
754
    {
755
    mBufferSize = size;
756
    }
757

    
758
///////////////////////////////////////////////////////////////////////////////////////////////////
759
// PUBLIC API
760
///////////////////////////////////////////////////////////////////////////////////////////////////
761
/**
762
 * Create empty effect queue.
763
 */
764
  public DistortedEffects()
765
    {
766
    mID = ++mNextID;
767
    initializeEffectLists(this,0);
768
    }
769

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

    
786
///////////////////////////////////////////////////////////////////////////////////////////////////
787
/**
788
 * Releases all resources. After this call, the queue should not be used anymore.
789
 */
790
  @SuppressWarnings("unused")
791
  public synchronized void delete()
792
    {
793
    releasePriv();
794
    }
795

    
796
///////////////////////////////////////////////////////////////////////////////////////////////////
797
/**
798
 * Returns unique ID of this instance.
799
 *
800
 * @return ID of the object.
801
 */
802
  public long getID()
803
      {
804
      return mID;
805
      }
806

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

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

    
838
///////////////////////////////////////////////////////////////////////////////////////////////////
839
/**
840
 * Aborts all Effects.
841
 * @return Number of effects aborted.
842
 */
843
  public int abortAllEffects()
844
    {
845
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
846
    }
847

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

    
867
///////////////////////////////////////////////////////////////////////////////////////////////////
868
/**
869
 * Aborts an Effect by its ID.
870
 *
871
 * @param id the Id of the Effect to be removed, as returned by getID().
872
 * @return Number of effects aborted.
873
 */
874
  public int abortById(long id)
875
    {
876
    long type = id&EffectType.MASK;
877

    
878
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
879
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
880
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
881
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
882

    
883
    return 0;
884
    }
885

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

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

    
924
///////////////////////////////////////////////////////////////////////////////////////////////////
925
/**
926
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
927
 * single (InputSurface,MeshBase) combo.
928
 *
929
 * @param type {@link EffectType}
930
 * @return The maximum number of effects of a given type.
931
 */
932
  @SuppressWarnings("unused")
933
  public static int getMax(EffectType type)
934
    {
935
    return EffectQueue.getMax(type.ordinal());
936
    }
937

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

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

    
978
    return false;
979
    }
980
  }
(3-3/17)