Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedEffects.java @ 031fbe7a

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.message.EffectListener;
33
import org.distorted.library.program.DistortedProgram;
34

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
140
///////////////////////////////////////////////////////////////////////////////////////////////////
141

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
357
///////////////////////////////////////////////////////////////////////////////////////////////////
358

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

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

    
406
///////////////////////////////////////////////////////////////////////////////////////////////////
407

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

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

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

    
423
///////////////////////////////////////////////////////////////////////////////////////////////////
424

    
425
  private void displayNormals(MeshObject mesh)
426
    {
427
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, mesh.mAttTFO[0]);
428
    GLES31.glBeginTransformFeedback( GLES31.GL_POINTS);
429
    DistortedRenderState.switchOffDrawing();
430
    GLES31.glDrawArrays( GLES31.GL_POINTS, 0, mesh.numVertices);
431
    DistortedRenderState.restoreDrawing();
432
    GLES31.glEndTransformFeedback();
433
    GLES31.glBindBufferBase(GLES31.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
434

    
435
    mNormalProgram.useProgram();
436
    GLES31.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, mM.getMVP() , 0);
437
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttTFO[0]);
438
    GLES31.glVertexAttribPointer(mNormalProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, 0, 0);
439
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
440
    GLES31.glLineWidth(8.0f);
441
    GLES31.glDrawArrays(GLES31.GL_LINES, 0, 2*mesh.numVertices);
442
    }
443

    
444
///////////////////////////////////////////////////////////////////////////////////////////////////
445

    
446
  void drawPrivOIT(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime, float marginInPixels)
447
    {
448
    float halfZ = halfW*mesh.zFactor;
449

    
450
    mM.compute(currTime);
451
    mV.compute(currTime,halfW,halfH,halfZ);
452
    mF.compute(currTime,halfW,halfH);
453
    mP.compute(currTime);
454

    
455
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
456

    
457
    mMainOITProgram.useProgram();
458
    GLES31.glUniform1i(mMainOITTextureH, 0);
459
    GLES31.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
460
    GLES31.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
461

    
462
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttVBO[0]);
463
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
464
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
465
    GLES31.glVertexAttribPointer(mMainOITProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
466
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
467

    
468
    mM.send(surface,halfW,halfH,halfZ,marginInPixels,1);
469
    mV.send(1);
470
    mF.send(1);
471

    
472
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
473

    
474
    if( mesh.mShowNormals ) displayNormals(mesh);
475
    }
476

    
477
///////////////////////////////////////////////////////////////////////////////////////////////////
478

    
479
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime, float marginInPixels)
480
    {
481
    float halfZ = halfW*mesh.zFactor;
482

    
483
    mM.compute(currTime);
484
    mV.compute(currTime,halfW,halfH,halfZ);
485
    mF.compute(currTime,halfW,halfH);
486
    mP.compute(currTime);
487

    
488
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
489

    
490
    mMainProgram.useProgram();
491
    GLES31.glUniform1i(mMainTextureH, 0);
492

    
493
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, mesh.mAttVBO[0]);
494
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
495
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
496
    GLES31.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES31.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
497
    GLES31.glBindBuffer(GLES31.GL_ARRAY_BUFFER, 0);
498

    
499
    mM.send(surface,halfW,halfH,halfZ,marginInPixels,0);
500
    mV.send(0);
501
    mF.send(0);
502

    
503
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
504

    
505
    if( mesh.mShowNormals ) displayNormals(mesh);
506
    }
507

    
508
///////////////////////////////////////////////////////////////////////////////////////////////////
509
/**
510
 * Only for use by the library itself.
511
 *
512
 * @y.exclude
513
 */
514
  public static void blitPriv(DistortedOutputSurface surface)
515
    {
516
    mBlitProgram.useProgram();
517

    
518
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
519
    GLES31.glUniform1i(mBlitTextureH, 0);
520
    GLES31.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
521
    GLES31.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
522
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
523
    }
524

    
525
///////////////////////////////////////////////////////////////////////////////////////////////////
526

    
527
  static void blitDepthPriv(DistortedOutputSurface surface, float corrW, float corrH)
528
    {
529
    mBlitDepthProgram.useProgram();
530

    
531
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
532
    GLES31.glUniform1i(mBlitDepthTextureH, 0);
533
    GLES31.glUniform1i(mBlitDepthDepthTextureH, 1);
534
    GLES31.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
535
    GLES31.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
536
    GLES31.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
537
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
538
    }
539

    
540
///////////////////////////////////////////////////////////////////////////////////////////////////
541

    
542
  private static int printPreviousBuffer()
543
    {
544
    int counter = 0;
545

    
546
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
547
                                                                GLES31.GL_MAP_READ_BIT);
548
    if( atomicBuf!=null )
549
      {
550
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
551
      counter = atomicIntBuf.get(0);
552
      }
553
    else
554
      {
555
      android.util.Log.e("effects", "print: failed to map atomic buffer");
556
      }
557

    
558
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
559

    
560
    return counter;
561
    }
562

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

    
565
  private static void zeroBuffer()
566
    {
567
    ByteBuffer atomicBuf = (ByteBuffer)GLES31.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
568
        GLES31.GL_MAP_WRITE_BIT|GLES31.GL_MAP_INVALIDATE_BUFFER_BIT);
569
    if( atomicBuf!=null )
570
      {
571
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
572
      atomicIntBuf.put(0,0);
573
      }
574
    else
575
      {
576
      android.util.Log.e("effects", "zero: failed to map atomic buffer");
577
      }
578

    
579
    GLES31.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
580
    }
581

    
582
///////////////////////////////////////////////////////////////////////////////////////////////////
583
// reset atomic counter to 0
584

    
585
  static int zeroOutAtomic()
586
    {
587
    int counter = 0;
588

    
589
    if( mAtomicCounter[0]<0 )
590
      {
591
      GLES31.glGenBuffers(Distorted.FBO_QUEUE_SIZE,mAtomicCounter,0);
592

    
593
      for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++)
594
        {
595
        GLES31.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
596
        GLES31.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES31.GL_DYNAMIC_DRAW);
597
        zeroBuffer();
598
        }
599
      }
600

    
601
    // reading the value of the buffer on every frame would slow down rendering by
602
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
603
    if( mCurrBuffer==0 )
604
      {
605
      GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
606
      counter = printPreviousBuffer();
607
      }
608

    
609
    if( ++mCurrBuffer>=Distorted.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
610

    
611
    GLES31.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
612
    zeroBuffer();
613

    
614
    return counter;
615
    }
616

    
617
///////////////////////////////////////////////////////////////////////////////////////////////////
618
// Pass1 of the OIT algorithm. Clear per-pixel head-poiners.
619

    
620
  static void oitClear(DistortedOutputSurface surface, int counter)
621
    {
622
    if( mLinkedListSSBO[0]<0 )
623
      {
624
      GLES31.glGenBuffers(1,mLinkedListSSBO,0);
625

    
626
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
627
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
628
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES31.GL_DYNAMIC_READ|GLES31.GL_DYNAMIC_DRAW);
629
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
630

    
631
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
632
      }
633

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

    
638
    if( overflow>1.0f )
639
      {
640
      //android.util.Log.e("effects", "previous frame rendered "+counter+
641
      //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
642

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

    
650
    mOITClearProgram.useProgram();
651

    
652
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
653
    GLES31.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
654
    GLES31.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
655
    GLES31.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
656
    GLES31.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
657
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
658
    }
659

    
660
///////////////////////////////////////////////////////////////////////////////////////////////////
661
// Pass2 of the OIT algorithm - build per-pixel linked lists.
662

    
663
  static void oitBuild(DistortedOutputSurface surface, float corrW, float corrH)
664
    {
665
    mOITBuildProgram.useProgram();
666

    
667
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
668
    GLES31.glUniform1i(mOITBuildTextureH, 0);
669
    GLES31.glUniform1i(mOITBuildDepthTextureH, 1);
670
    GLES31.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
671
    GLES31.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
672
    GLES31.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
673
    GLES31.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
674
    GLES31.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
675
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
676
    }
677

    
678
///////////////////////////////////////////////////////////////////////////////////////////////////
679
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
680

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

    
685
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
686
    GLES31.glUniform1i(mOITCollapseDepthTextureH, 1);
687
    GLES31.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
688
    GLES31.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
689
    GLES31.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
690
    GLES31.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
691
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
692
    }
693

    
694
///////////////////////////////////////////////////////////////////////////////////////////////////
695
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
696

    
697
  static void oitRender(DistortedOutputSurface surface, float corrW, float corrH)
698
    {
699
    mOITRenderProgram.useProgram();
700

    
701
    GLES31.glViewport(0, 0, surface.mWidth, surface.mHeight );
702
    GLES31.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
703
    GLES31.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
704
    GLES31.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
705
    GLES31.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES31.GL_FLOAT, false, 0, mQuadPositions);
706
    GLES31.glDrawArrays(GLES31.GL_TRIANGLE_STRIP, 0, 4);
707
    }
708

    
709
///////////////////////////////////////////////////////////////////////////////////////////////////
710

    
711
  private void releasePriv()
712
    {
713
    if( !matrixCloned      ) mM.abortAll(false);
714
    if( !vertexCloned      ) mV.abortAll(false);
715
    if( !fragmentCloned    ) mF.abortAll(false);
716
    if( !postprocessCloned ) mP.abortAll(false);
717

    
718
    mM = null;
719
    mV = null;
720
    mF = null;
721
    mP = null;
722
    }
723

    
724
///////////////////////////////////////////////////////////////////////////////////////////////////
725

    
726
  static void onPause()
727
    {
728
    mLinkedListSSBO[0]= -1;
729

    
730
    for(int i=0; i<Distorted.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
731
    }
732

    
733
///////////////////////////////////////////////////////////////////////////////////////////////////
734

    
735
  static void onDestroy()
736
    {
737
    mNextID =  0;
738
    }
739

    
740
///////////////////////////////////////////////////////////////////////////////////////////////////
741

    
742
  static void setSSBOSize(float size)
743
    {
744
    mBufferSize = size;
745
    }
746

    
747
///////////////////////////////////////////////////////////////////////////////////////////////////
748
// PUBLIC API
749
///////////////////////////////////////////////////////////////////////////////////////////////////
750
/**
751
 * Create empty effect queue.
752
 */
753
  public DistortedEffects()
754
    {
755
    mID = ++mNextID;
756
    initializeEffectLists(this,0);
757
    }
758

    
759
///////////////////////////////////////////////////////////////////////////////////////////////////
760
/**
761
 * Copy constructor.
762
 * <p>
763
 * Whatever we do not clone gets created just like in the default constructor.
764
 *
765
 * @param dc    Source object to create our object from
766
 * @param flags A bitmask of values specifying what to copy.
767
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
768
 */
769
  public DistortedEffects(DistortedEffects dc, int flags)
770
    {
771
    mID = ++mNextID;
772
    initializeEffectLists(dc,flags);
773
    }
774

    
775
///////////////////////////////////////////////////////////////////////////////////////////////////
776
/**
777
 * Releases all resources. After this call, the queue should not be used anymore.
778
 */
779
  @SuppressWarnings("unused")
780
  public synchronized void delete()
781
    {
782
    releasePriv();
783
    }
784

    
785
///////////////////////////////////////////////////////////////////////////////////////////////////
786
/**
787
 * Returns unique ID of this instance.
788
 *
789
 * @return ID of the object.
790
 */
791
  public long getID()
792
      {
793
      return mID;
794
      }
795

    
796
///////////////////////////////////////////////////////////////////////////////////////////////////
797
/**
798
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
799
 * to one of the Effects in our queues. Nothing will happen if 'el' is already in the list.
800
 * 
801
 * @param el A class implementing the EffectListener interface that wants to get notifications.
802
 */
803
  @SuppressWarnings("unused")
804
  public void registerForMessages(EffectListener el)
805
    {
806
    mM.registerForMessages(el);
807
    mV.registerForMessages(el);
808
    mF.registerForMessages(el);
809
    mP.registerForMessages(el);
810
    }
811

    
812
///////////////////////////////////////////////////////////////////////////////////////////////////
813
/**
814
 * Removes the calling class from the list of Listeners that get notified if something happens to Effects in our queue.
815
 * 
816
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
817
 */
818
  @SuppressWarnings("unused")
819
  public void deregisterForMessages(EffectListener el)
820
    {
821
    mM.deregisterForMessages(el);
822
    mV.deregisterForMessages(el);
823
    mF.deregisterForMessages(el);
824
    mP.deregisterForMessages(el);
825
    }
826

    
827
///////////////////////////////////////////////////////////////////////////////////////////////////
828
/**
829
 * Aborts all Effects.
830
 * @return Number of effects aborted.
831
 */
832
  public int abortAllEffects()
833
    {
834
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
835
    }
836

    
837
///////////////////////////////////////////////////////////////////////////////////////////////////
838
/**
839
 * Aborts all Effects of a given type, for example all MATRIX Effects.
840
 * 
841
 * @param type one of the constants defined in {@link EffectType}
842
 * @return Number of effects aborted.
843
 */
844
  public int abortByType(EffectType type)
845
    {
846
    switch(type)
847
      {
848
      case MATRIX     : return mM.abortAll(true);
849
      case VERTEX     : return mV.abortAll(true);
850
      case FRAGMENT   : return mF.abortAll(true);
851
      case POSTPROCESS: return mP.abortAll(true);
852
      default         : return 0;
853
      }
854
    }
855

    
856
///////////////////////////////////////////////////////////////////////////////////////////////////
857
/**
858
 * Aborts an Effect by its ID.
859
 *
860
 * @param id the Id of the Effect to be removed, as returned by getID().
861
 * @return Number of effects aborted.
862
 */
863
  public int abortById(long id)
864
    {
865
    long type = id&EffectType.MASK;
866

    
867
    if( type == EffectType.MATRIX.ordinal()      ) return mM.removeById(id);
868
    if( type == EffectType.VERTEX.ordinal()      ) return mV.removeById(id);
869
    if( type == EffectType.FRAGMENT.ordinal()    ) return mF.removeById(id);
870
    if( type == EffectType.POSTPROCESS.ordinal() ) return mP.removeById(id);
871

    
872
    return 0;
873
    }
874

    
875
///////////////////////////////////////////////////////////////////////////////////////////////////
876
/**
877
 * Aborts a single Effect.
878
 * 
879
 * @param effect the Effect we want to abort.
880
 * @return number of Effects aborted. Always either 0 or 1.
881
 */
882
  public int abortEffect(Effect effect)
883
    {
884
    switch(effect.getType())
885
      {
886
      case MATRIX     : return mM.removeEffect(effect);
887
      case VERTEX     : return mV.removeEffect(effect);
888
      case FRAGMENT   : return mF.removeEffect(effect);
889
      case POSTPROCESS: return mP.removeEffect(effect);
890
      default         : return 0;
891
      }
892
    }
893

    
894
///////////////////////////////////////////////////////////////////////////////////////////////////
895
/**
896
 * Abort all Effects of a given name, for example all rotations.
897
 * 
898
 * @param name one of the constants defined in {@link EffectName}
899
 * @return number of Effects aborted.
900
 */
901
  public int abortByName(EffectName name)
902
    {
903
    switch(name.getType())
904
      {
905
      case MATRIX     : return mM.removeByName(name);
906
      case VERTEX     : return mV.removeByName(name);
907
      case FRAGMENT   : return mF.removeByName(name);
908
      case POSTPROCESS: return mP.removeByName(name);
909
      default                : return 0;
910
      }
911
    }
912

    
913
///////////////////////////////////////////////////////////////////////////////////////////////////
914
/**
915
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
916
 * single (InputSurface,MeshObject) combo.
917
 *
918
 * @param type {@link EffectType}
919
 * @return The maximum number of effects of a given type.
920
 */
921
  @SuppressWarnings("unused")
922
  public static int getMax(EffectType type)
923
    {
924
    return EffectQueue.getMax(type.ordinal());
925
    }
926

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

    
950
///////////////////////////////////////////////////////////////////////////////////////////////////
951
/**
952
 * Add a new Effect to our queue.
953
 *
954
 * @param effect The Effect to add.
955
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
956
 */
957
  public boolean apply(Effect effect)
958
    {
959
    switch(effect.getType())
960
      {
961
      case MATRIX      : return mM.add(effect);
962
      case VERTEX      : return mV.add(effect);
963
      case FRAGMENT    : return mF.add(effect);
964
      case POSTPROCESS : return mP.add(effect);
965
      }
966

    
967
    return false;
968
    }
969
  }
(2-2/20)