Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedEffects.java @ a0397f32

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 EffectQueue[] mQueues;
135

    
136
///////////////////////////////////////////////////////////////////////////////////////////////////
137

    
138
  static void createPrograms(Resources resources)
139
    {
140
    // MAIN PROGRAM ////////////////////////////////////
141
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
142
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
143

    
144
    int numF = FragmentEffect.getNumEnabled();
145
    int numV = VertexEffect.getNumEnabled();
146

    
147
    String mainVertHeader= Distorted.GLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
148
    String mainFragHeader= Distorted.GLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
149
    String enabledEffectV= VertexEffect.getGLSL();
150
    String enabledEffectF= FragmentEffect.getGLSL();
151

    
152
    String[] feedback = { "v_Position", "v_endPosition" };
153

    
154
    try
155
      {
156
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
157
                                          enabledEffectV, enabledEffectF, Distorted.GLSL, feedback);
158
      }
159
    catch(Exception e)
160
      {
161
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
162
      throw new RuntimeException(e.getMessage());
163
      }
164

    
165
    int mainProgramH = mMainProgram.getProgramHandle();
166
    EffectQueue.getUniforms(mainProgramH,0);
167
    mMainTextureH= GLES31.glGetUniformLocation( mainProgramH, "u_Texture");
168

    
169
    // BLIT PROGRAM ////////////////////////////////////
170
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
171
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
172

    
173
    try
174
      {
175
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
176
      }
177
    catch(Exception e)
178
      {
179
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
180
      throw new RuntimeException(e.getMessage());
181
      }
182

    
183
    int blitProgramH = mBlitProgram.getProgramHandle();
184
    mBlitTextureH  = GLES31.glGetUniformLocation( blitProgramH, "u_Texture");
185
    mBlitDepthH    = GLES31.glGetUniformLocation( blitProgramH, "u_Depth");
186

    
187
    // BLIT DEPTH PROGRAM ////////////////////////////////////
188
    final InputStream blitDepthVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
189
    final InputStream blitDepthFragStream = resources.openRawResource(R.raw.blit_depth_fragment_shader);
190

    
191
    try
192
      {
193
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
194
      }
195
    catch(Exception e)
196
      {
197
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
198
      throw new RuntimeException(e.getMessage());
199
      }
200

    
201
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
202
    mBlitDepthTextureH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Texture");
203
    mBlitDepthDepthTextureH = GLES31.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
204
    mBlitDepthDepthH        = GLES31.glGetUniformLocation( blitDepthProgramH, "u_Depth");
205
    mBlitDepthTexCorrH      = GLES31.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
206

    
207
    // NORMAL PROGRAM //////////////////////////////////////
208
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
209
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
210

    
211
    try
212
      {
213
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, Distorted.GLSL_VERSION, Distorted.GLSL_VERSION, Distorted.GLSL);
214
      }
215
    catch(Exception e)
216
      {
217
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
218
      throw new RuntimeException(e.getMessage());
219
      }
220

    
221
    int normalProgramH = mNormalProgram.getProgramHandle();
222
    mNormalMVPMatrixH  = GLES31.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
223
    }
224

    
225
///////////////////////////////////////////////////////////////////////////////////////////////////
226

    
227
  static void createProgramsOIT(Resources resources)
228
    {
229
    // MAIN OIT PROGRAM ////////////////////////////////
230
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
231
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
232

    
233
    int numF = FragmentEffect.getNumEnabled();
234
    int numV = VertexEffect.getNumEnabled();
235

    
236
    String mainVertHeader= Distorted.GLSL_VERSION +
237
                           ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") +
238
                           ("#define OIT\n");
239
    String mainFragHeader= Distorted.GLSL_VERSION +
240
                           ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") +
241
                           ("#define OIT\n");
242

    
243
    String enabledEffectV= VertexEffect.getGLSL();
244
    String enabledEffectF= FragmentEffect.getGLSL();
245

    
246
    try
247
      {
248
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
249
                                             enabledEffectV, enabledEffectF, Distorted.GLSL, null);
250
      }
251
    catch(Exception e)
252
      {
253
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
254
      throw new RuntimeException(e.getMessage());
255
      }
256

    
257
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
258
    EffectQueue.getUniforms(mainOITProgramH,1);
259
    mMainOITTextureH    = GLES31.glGetUniformLocation( mainOITProgramH, "u_Texture");
260
    mMainOITSizeH       = GLES31.glGetUniformLocation( mainOITProgramH, "u_Size");
261
    mMainOITNumRecordsH = GLES31.glGetUniformLocation( mainOITProgramH, "u_numRecords");
262

    
263
    // OIT CLEAR PROGRAM ////////////////////////////////////
264
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
265
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
266

    
267
    try
268
      {
269
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
270
      }
271
    catch(Exception e)
272
      {
273
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
274
      throw new RuntimeException(e.getMessage());
275
      }
276

    
277
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
278
    mOITClearDepthH        = GLES31.glGetUniformLocation( oitClearProgramH, "u_Depth");
279
    mOITClearTexCorrH      = GLES31.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
280
    mOITClearSizeH         = GLES31.glGetUniformLocation( oitClearProgramH, "u_Size");
281

    
282
    // OIT BUILD PROGRAM ////////////////////////////////////
283
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
284
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
285

    
286
    try
287
      {
288
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
289
      }
290
    catch(Exception e)
291
      {
292
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
293
      throw new RuntimeException(e.getMessage());
294
      }
295

    
296
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
297
    mOITBuildTextureH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Texture");
298
    mOITBuildDepthTextureH = GLES31.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
299
    mOITBuildDepthH        = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Depth");
300
    mOITBuildTexCorrH      = GLES31.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
301
    mOITBuildSizeH         = GLES31.glGetUniformLocation( oitBuildProgramH, "u_Size");
302
    mOITBuildNumRecordsH   = GLES31.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
303

    
304
    // OIT COLLAPSE PROGRAM ///////////////////////////
305
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
306
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
307

    
308
    try
309
      {
310
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
311
      }
312
    catch(Exception e)
313
      {
314
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
315
      throw new RuntimeException(e.getMessage());
316
      }
317

    
318
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
319
    mOITCollapseDepthTextureH = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
320
    mOITCollapseDepthH        = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
321
    mOITCollapseTexCorrH      = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
322
    mOITCollapseSizeH         = GLES31.glGetUniformLocation( oitCollapseProgramH, "u_Size");
323

    
324
    // OIT RENDER PROGRAM ///////////////////////////
325
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
326
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
327

    
328
    try
329
      {
330
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream,Distorted.GLSL_VERSION,Distorted.GLSL_VERSION, Distorted.GLSL);
331
      }
332
    catch(Exception e)
333
      {
334
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
335
      throw new RuntimeException(e.getMessage());
336
      }
337

    
338
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
339
    mOITRenderDepthH        = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Depth");
340
    mOITRenderTexCorrH      = GLES31.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
341
    mOITRenderSizeH         = GLES31.glGetUniformLocation( oitRenderProgramH, "u_Size");
342
    }
343

    
344
///////////////////////////////////////////////////////////////////////////////////////////////////
345

    
346
  EffectQueue[] getQueues()
347
    {
348
    return mQueues;
349
    }
350

    
351
///////////////////////////////////////////////////////////////////////////////////////////////////
352

    
353
  void newNode(DistortedNode node)
354
    {
355
    EffectQueue.newNode(mQueues,node);
356
    }
357

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

    
360
  void removeNode(DistortedNode node)
361
    {
362
    EffectQueue.removeNode(mQueues,node);
363
    }
364

    
365
///////////////////////////////////////////////////////////////////////////////////////////////////
366

    
367
  private void displayNormals(MeshBase mesh)
368
    {
369
    int num = mesh.getNumVertices();
370
    int tfo = mesh.getTFO();
371

    
372
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
373
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
374
    DistortedRenderState.switchOffDrawing();
375
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, num );
376
    DistortedRenderState.restoreDrawing();
377
    GLES31.glEndTransformFeedback();
378
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
379

    
380
    mNormalProgram.useProgram();
381
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, EffectQueue.getMVP(mQueues) , 0);
382
    mesh.bindTransformAttribs(mNormalProgram);
383
    GLES31.glLineWidth(8.0f);
384
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*num);
385
    }
386

    
387
///////////////////////////////////////////////////////////////////////////////////////////////////
388

    
389
  void drawPrivOIT(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
390
    {
391
    float halfZ = halfW*mesh.getZFactor();
392

    
393
    EffectQueue.compute(mQueues, currTime, halfW, halfH, halfZ );
394
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
395

    
396
    mMainOITProgram.useProgram();
397
    GLES31.glUniform1i(mMainOITTextureH, 0);
398
    GLES31.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
399
    GLES31.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
400

    
401
    mesh.bindVertexAttribs(mMainOITProgram);
402

    
403
    float inflate = mesh.getInflate();
404

    
405
    EffectQueue.send(mQueues, surface, inflate, halfW, halfH, halfZ, 1 );
406
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
407

    
408
    if( mesh.getShowNormals() )
409
      {
410
      mMainProgram.useProgram();
411
      EffectQueue.send(mQueues, surface, inflate, halfW, halfH, halfZ, 0 );
412
      displayNormals(mesh);
413
      }
414
    }
415

    
416
///////////////////////////////////////////////////////////////////////////////////////////////////
417

    
418
  void drawPriv(float halfW, float halfH, MeshBase mesh, DistortedOutputSurface surface, long currTime)
419
    {
420
    float halfZ = halfW*mesh.getZFactor();
421

    
422
    EffectQueue.compute(mQueues, currTime, halfW, halfH, halfZ );
423
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
424
    mMainProgram.useProgram();
425
    GLES31.glUniform1i(mMainTextureH, 0);
426
    mesh.bindVertexAttribs(mMainProgram);
427
    EffectQueue.send(mQueues, surface, mesh.getInflate(), halfW, halfH, halfZ, 0 );
428
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
429

    
430
    if( mesh.getShowNormals() ) displayNormals(mesh);
431
    }
432

    
433
///////////////////////////////////////////////////////////////////////////////////////////////////
434

    
435
  static void blitPriv(DistortedOutputSurface surface)
436
    {
437
    mBlitProgram.useProgram();
438

    
439
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
440
    GLES31.glUniform1i(mBlitTextureH, 0);
441
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
442
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
443
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
444
    }
445

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

    
448
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
449
    {
450
    mBlitDepthProgram.useProgram();
451

    
452
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
453
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
454
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
455
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
456
    GLES31.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
457
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
458
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
459
    }
460

    
461
///////////////////////////////////////////////////////////////////////////////////////////////////
462

    
463
  private static int printPreviousBuffer()
464
    {
465
    int counter = 0;
466

    
467
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
468
                                                                GLES31.GL_MAP_READ_BIT);
469
    if( atomicBuf!=null )
470
      {
471
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
472
      counter = atomicIntBuf.get(0);
473
      }
474
    else
475
      {
476
      android.util.Log.e("effects", "print: failed to map atomic buffer");
477
      }
478

    
479
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
480

    
481
    return counter;
482
    }
483

    
484
///////////////////////////////////////////////////////////////////////////////////////////////////
485

    
486
  private static void zeroBuffer()
487
    {
488
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
489
        GLES31.GL_MAP_WRITE_BIT|GLES31.GL_MAP_INVALIDATE_BUFFER_BIT);
490
    if( atomicBuf!=null )
491
      {
492
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
493
      atomicIntBuf.put(0,0);
494
      }
495
    else
496
      {
497
      android.util.Log.e("effects", "zero: failed to map atomic buffer");
498
      }
499

    
500
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
501
    }
502

    
503
///////////////////////////////////////////////////////////////////////////////////////////////////
504
// reset atomic counter to 0
505

    
506
  static int zeroOutAtomic()
507
    {
508
    int counter = 0;
509

    
510
    if( mAtomicCounter[0]<0 )
511
      {
512
      GLES31.glGenBuffers(Distorted.FBO_QUEUE_SIZE,mAtomicCounter,0);
513

    
514
      for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)
515
        {
516
        GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
517
        GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
518
        zeroBuffer();
519
        }
520
      }
521

    
522
    // reading the value of the buffer on every frame would slow down rendering by
523
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
524
    if( mCurrBuffer==0 )
525
      {
526
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
527
      counter = printPreviousBuffer();
528
      }
529

    
530
    if( ++mCurrBuffer>=Distorted.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
531

    
532
    GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
533
    zeroBuffer();
534

    
535
    return counter;
536
    }
537

    
538
///////////////////////////////////////////////////////////////////////////////////////////////////
539
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
540

    
541
  static void oitClear(DistortedOutputSurface surface, int counter)
542
    {
543
    if( mLinkedListSSBO[0]<0 )
544
      {
545
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
546

    
547
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
548
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
549
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
550
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
551

    
552
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
553
      }
554

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

    
559
    if( overflow>1.0f )
560
      {
561
      //android.util.Log.e("effects", "previous frame rendered "+counter+
562
      //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
563

    
564
      mBufferSize *= (int)(overflow+1.0f);
565
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
566
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
567
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
568
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
569
      }
570

    
571
    mOITClearProgram.useProgram();
572

    
573
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
574
    GLES31.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
575
    GLES31.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
576
    GLES31.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
577
    GLES31.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
578
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
579
    }
580

    
581
///////////////////////////////////////////////////////////////////////////////////////////////////
582
// Pass2 of the OIT algorithm - build per-pixel linked lists.
583

    
584
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
585
    {
586
    mOITBuildProgram.useProgram();
587

    
588
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
589
    GLES31.glUniform1i(mOITBuildTextureH, 0);
590
    GLES31.glUniform1i(mOITBuildDepthTextureH, 1);
591
    GLES31.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
592
    GLES31.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
593
    GLES31.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
594
    GLES31.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
595
    GLES31.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
596
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
597
    }
598

    
599
///////////////////////////////////////////////////////////////////////////////////////////////////
600
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
601

    
602
  static void oitCollapse(DistortedOutputSurface surface, float corrW, float corrH)
603
    {
604
    mOITCollapseProgram.useProgram();
605

    
606
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
607
    GLES31.glUniform1i(mOITCollapseDepthTextureH, 1);
608
    GLES31.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
609
    GLES31.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
610
    GLES31.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
611
    GLES31.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
612
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
613
    }
614

    
615
///////////////////////////////////////////////////////////////////////////////////////////////////
616
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
617

    
618
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
619
    {
620
    mOITRenderProgram.useProgram();
621

    
622
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
623
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
624
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
625
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
626
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
627
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
628
    }
629

    
630
///////////////////////////////////////////////////////////////////////////////////////////////////
631

    
632
  static void onPause()
633
    {
634
    mLinkedListSSBO[0]= -1;
635

    
636
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
637
    }
638

    
639
///////////////////////////////////////////////////////////////////////////////////////////////////
640

    
641
  static void onDestroy()
642
    {
643
    mNextID =  0;
644
    }
645

    
646
///////////////////////////////////////////////////////////////////////////////////////////////////
647

    
648
  static void setSSBOSize(float size)
649
    {
650
    mBufferSize = size;
651
    }
652

    
653
///////////////////////////////////////////////////////////////////////////////////////////////////
654
// PUBLIC API
655
///////////////////////////////////////////////////////////////////////////////////////////////////
656
/**
657
 * Create empty effect queue.
658
 */
659
  public DistortedEffects()
660
    {
661
    mID = ++mNextID;
662
    mQueues = new EffectQueue[EffectType.LENGTH];
663
    EffectQueue.allocateQueues(mQueues,null,0,mID);
664
    }
665

    
666
///////////////////////////////////////////////////////////////////////////////////////////////////
667
/**
668
 * Copy constructor.
669
 * <p>
670
 * Whatever we do not clone gets created just like in the default constructor.
671
 *
672
 * @param dc    Source object to create our object from
673
 * @param flags A bitmask of values specifying what to copy.
674
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
675
 */
676
  public DistortedEffects(DistortedEffects dc, int flags)
677
    {
678
    mID = ++mNextID;
679
    mQueues = new EffectQueue[EffectType.LENGTH];
680
    EffectQueue.allocateQueues(mQueues,dc.getQueues(),flags,mID);
681
    }
682

    
683
///////////////////////////////////////////////////////////////////////////////////////////////////
684
/**
685
 * Returns unique ID of this instance.
686
 *
687
 * @return ID of the object.
688
 */
689
  public long getID()
690
      {
691
      return mID;
692
      }
693

    
694
///////////////////////////////////////////////////////////////////////////////////////////////////
695
/**
696
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
697
 * to one of the Effects in our queues. Nothing will happen if 'el' is already in the list.
698
 * 
699
 * @param el A class implementing the EffectListener interface that wants to get notifications.
700
 */
701
  @SuppressWarnings("unused")
702
  public void registerForMessages(EffectListener el)
703
    {
704
    for( int i=0; i<EffectType.LENGTH; i++)
705
      {
706
      mQueues[i].registerForMessages(el);
707
      }
708
    }
709

    
710
///////////////////////////////////////////////////////////////////////////////////////////////////
711
/**
712
 * Removes the calling class from the list of Listeners that get notified if something happens to Effects in our queue.
713
 * 
714
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
715
 */
716
  @SuppressWarnings("unused")
717
  public void deregisterForMessages(EffectListener el)
718
    {
719
    for( int i=0; i<EffectType.LENGTH; i++)
720
      {
721
      mQueues[i].deregisterForMessages(el);
722
      }
723
    }
724

    
725
///////////////////////////////////////////////////////////////////////////////////////////////////
726
/**
727
 * Aborts all Effects.
728
 * @return Number of effects aborted.
729
 */
730
  public int abortAllEffects()
731
    {
732
    int aborted = 0;
733

    
734
    for( int i=0; i<EffectType.LENGTH; i++)
735
      {
736
      aborted += mQueues[i].abortAll(true);
737
      }
738

    
739
    return aborted;
740
    }
741

    
742
///////////////////////////////////////////////////////////////////////////////////////////////////
743
/**
744
 * Aborts all Effects of a given type, for example all MATRIX Effects.
745
 * 
746
 * @param type one of the constants defined in {@link EffectType}
747
 * @return Number of effects aborted.
748
 */
749
  public int abortByType(EffectType type)
750
    {
751
    int num = type.ordinal();
752
    return mQueues[num].abortAll(true);
753
    }
754

    
755
///////////////////////////////////////////////////////////////////////////////////////////////////
756
/**
757
 * Aborts an Effect by its ID.
758
 *
759
 * @param id the Id of the Effect to be removed, as returned by getID().
760
 * @return Number of effects aborted.
761
 */
762
  public int abortById(long id)
763
    {
764
    int num = (int)(id&EffectType.MASK);
765
    return mQueues[num].removeById(id);
766
    }
767

    
768
///////////////////////////////////////////////////////////////////////////////////////////////////
769
/**
770
 * Aborts a single Effect.
771
 * 
772
 * @param effect the Effect we want to abort.
773
 * @return number of Effects aborted. Always either 0 or 1.
774
 */
775
  public int abortEffect(Effect effect)
776
    {
777
    int num = effect.getType().ordinal();
778
    return mQueues[num].removeEffect(effect);
779
    }
780

    
781
///////////////////////////////////////////////////////////////////////////////////////////////////
782
/**
783
 * Abort all Effects of a given name, for example all rotations.
784
 * 
785
 * @param name one of the constants defined in {@link EffectName}
786
 * @return number of Effects aborted.
787
 */
788
  public int abortByName(EffectName name)
789
    {
790
    int num = name.getType().ordinal();
791
    return mQueues[num].removeByName(name);
792
    }
793

    
794
///////////////////////////////////////////////////////////////////////////////////////////////////
795
/**
796
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
797
 * single (InputSurface,MeshBase) combo.
798
 *
799
 * @param type {@link EffectType}
800
 * @return The maximum number of effects of a given type.
801
 */
802
  @SuppressWarnings("unused")
803
  public static int getMax(EffectType type)
804
    {
805
    return EffectQueue.getMax(type.ordinal());
806
    }
807

    
808
///////////////////////////////////////////////////////////////////////////////////////////////////
809
/**
810
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
811
 * This can fail if:
812
 * <ul>
813
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
814
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
815
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
816
 *     time only decreasing the value of 'max' is permitted.
817
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
818
 * </ul>
819
 *
820
 * @param type {@link EffectType}
821
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
822
 *            than Byte.MAX_VALUE
823
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
824
 */
825
  @SuppressWarnings("unused")
826
  public static boolean setMax(EffectType type, int max)
827
    {
828
    return EffectQueue.setMax(type.ordinal(),max);
829
    }
830

    
831
///////////////////////////////////////////////////////////////////////////////////////////////////
832
/**
833
 * Add a new Effect to our queue.
834
 *
835
 * @param effect The Effect to add.
836
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
837
 */
838
  public boolean apply(Effect effect)
839
    {
840
    int num = effect.getType().ordinal();
841
    return mQueues[num].add(effect);
842
    }
843
  }
(4-4/19)