Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 72ef21f7

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.app.ActivityManager;
23
import android.content.Context;
24
import android.content.pm.ConfigurationInfo;
25
import android.content.res.Resources;
26
import android.opengl.GLES30;
27
import android.opengl.GLES31;
28
import android.util.Log;
29

    
30
import org.distorted.library.R;
31
import org.distorted.library.effect.Effect;
32
import org.distorted.library.effectqueue.EffectQueue;
33
import org.distorted.library.effectqueue.EffectQueuePostprocess;
34
import org.distorted.library.effect.EffectType;
35
import org.distorted.library.effect.FragmentEffect;
36
import org.distorted.library.effect.PostprocessEffect;
37
import org.distorted.library.effect.VertexEffect;
38
import org.distorted.library.effectqueue.EffectQueueVertex;
39
import org.distorted.library.mesh.DeferredJobs;
40
import org.distorted.library.mesh.MeshBase;
41
import org.distorted.library.message.EffectMessageSender;
42
import org.distorted.library.program.DistortedProgram;
43
import org.distorted.library.program.VertexCompilationException;
44
import org.distorted.library.type.Dynamic;
45

    
46
import java.io.InputStream;
47
import java.nio.ByteBuffer;
48
import java.nio.ByteOrder;
49
import java.nio.FloatBuffer;
50
import java.nio.IntBuffer;
51
import java.util.regex.Matcher;
52
import java.util.regex.Pattern;
53

    
54
///////////////////////////////////////////////////////////////////////////////////////////////////
55
/**
56
 * A singleton class used to control various global dialog_settings.
57
 */
58
public class DistortedLibrary
59
  {
60
  /**
61
   * When creating an instance of a DistortedTexture from another instance, clone the Bitmap that's
62
   * backing up our DistortedTexture.
63
   * <p>
64
   * This way we can have two DistortedTextures, both backed up by the same Bitmap, to which we can
65
   * apply different effects. Used in the copy constructor.
66
   */
67
  public static final int CLONE_SURFACE = 0x1;
68
  /**
69
   * When creating an instance of a DistortedEffects from another instance, clone the Matrix Effects.
70
   * <p>
71
   * This way we can have two different DistortedEffects sharing the MATRIX queue.
72
   */
73
  public static final int CLONE_MATRIX = 0x2;
74
  /**
75
   * When creating an instance of a DistortedEffects from another instance, clone the Vertex Effects.
76
   * <p>
77
   * This way we can have two different DistortedEffects sharing the VERTEX queue.
78
   */
79
  public static final int CLONE_VERTEX  = 0x4;
80
  /**
81
   * When creating an instance of a DistortedEffects from another instance, clone the Fragment Effects.
82
   * <p>
83
   * This way we can have two different DistortedEffects sharing the FRAGMENT queue.
84
   */
85
  public static final int CLONE_FRAGMENT= 0x8;
86
   /**
87
   * When creating an instance of a DistortedEffects from another instance, clone the PostProcess Effects.
88
   * <p>
89
   * This way we can have two different DistortedEffects sharing the POSTPROCESS queue.
90
   */
91
  public static final int CLONE_POSTPROCESS= 0x10;
92
  /**
93
   * When creating an instance of a DistortedNode from another instance, clone the children Nodes.
94
   * <p>
95
   * This is mainly useful for creating many similar sub-trees and rendering then at different places
96
   * on the screen with (optionally) different Effects.
97
   */
98
  public static final int CLONE_CHILDREN= 0x20;
99

    
100
  /**
101
   * When creating a DistortedScreen (which needs to have mFBOQueueSize FBOs attached), pass this
102
   * constant for 'numOfFBOs' and the number of backing FBOs will be taken from 'mFBOQueueSize'
103
   * (the value of which is most likely unknown at the time of creation of the Screen)
104
   */
105
  public static final int WAIT_FOR_FBO_QUEUE_SIZE = -1;
106
  /**
107
   * Work around bugs in ARM Mali driver by, instead to a single FBO, rendering to a circular queue
108
   * of mFBOQueueSize FBOs. (otherwise we sometimes get a 'full pipeline flush' and the end result
109
   * might be missing part of the Objects)
110
   *
111
   * This bug only exists on Mali driver r12. (or more precisely it's there in r12 but fixed in r22)
112
   *
113
   * https://community.arm.com/graphics/f/discussions/10285/opengl-es-3-1-on-mali-t880-flashes
114
   */
115
  private static int mFBOQueueSize;
116
  private static int mGLSL;
117
  private static String mGLSL_VERSION;
118
  private static boolean mOITCompilationAttempted;
119
  private static int mMaxTextureSize = Integer.MAX_VALUE;
120

    
121
  //////////////////////////////////////////////////////////////////////////////////////////////
122
  /// MAIN PROGRAM ///
123
  private static DistortedProgram mMainProgram;
124
  private static int mMainTextureH;
125
  private static int mTransformFeedbackH;
126

    
127
  /// NORMAL PROGRAM /////
128
  private static DistortedProgram mNormalProgram;
129
  private static int mNormalProjectionH;
130

    
131
  /// MAIN OIT PROGRAM ///
132
  private static DistortedProgram mMainOITProgram;
133
  private static int mMainOITTextureH;
134
  private static int mMainOITSizeH;
135
  private static int mMainOITNumRecordsH;
136

    
137
  /// BLIT PROGRAM ///
138
  private static DistortedProgram mBlitProgram;
139
  private static int mBlitTextureH;
140
  private static int mBlitDepthH;
141
  private static final FloatBuffer mQuadPositions;
142

    
143
  /// FULL PROGRAM ///
144
  private static DistortedProgram mFullProgram;
145

    
146
  static
147
    {
148
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
149
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
150
    mQuadPositions.put(positionData).position(0);
151
    }
152

    
153
  /// BLIT DEPTH PROGRAM ///
154
  private static DistortedProgram mBlitDepthProgram;
155
  private static int mBlitDepthTextureH;
156
  private static int mBlitDepthDepthTextureH;
157
  private static int mBlitDepthDepthH;
158
  private static int mBlitDepthTexCorrH;
159

    
160
  /// Program Handles ///
161
  private static int mMainProgramH, mFullProgramH, mMainOITProgramH;
162

    
163
  /// OIT SSBO BUFFER ///
164
  private static int[] mLinkedListSSBO = new int[1];
165
  private static int[] mAtomicCounter;
166
  private static int   mCurrBuffer;
167

    
168
  static
169
    {
170
    mLinkedListSSBO[0]= -1;
171
    mCurrBuffer       =  0;
172
    }
173

    
174
  ///////////////////////////////////////////////////////////////
175
  // meaning: allocate 1.0 screenful of places for transparent
176
  // fragments in the SSBO backing up the OIT render method.
177
  private static float mBufferSize=1.0f;
178

    
179
  /// OIT CLEAR PROGRAM ///
180
  private static DistortedProgram mOITClearProgram;
181
  private static int mOITClearDepthH;
182
  private static int mOITClearTexCorrH;
183
  private static int mOITClearSizeH;
184

    
185
  /// OIT BUILD PROGRAM ///
186
  private static DistortedProgram mOITBuildProgram;
187
  private static int mOITBuildTextureH;
188
  private static int mOITBuildDepthTextureH;
189
  private static int mOITBuildDepthH;
190
  private static int mOITBuildTexCorrH;
191
  private static int mOITBuildSizeH;
192
  private static int mOITBuildNumRecordsH;
193

    
194
  /// OIT COLLAPSE PROGRAM ///
195
  private static DistortedProgram mOITCollapseProgram;
196
  private static int mOITCollapseDepthTextureH;
197
  private static int mOITCollapseDepthH;
198
  private static int mOITCollapseTexCorrH;
199
  private static int mOITCollapseSizeH;
200

    
201
  /// OIT RENDER PROGRAM ///
202
  private static DistortedProgram mOITRenderProgram;
203
  private static int mOITRenderDepthH;
204
  private static int mOITRenderTexCorrH;
205
  private static int mOITRenderSizeH;
206

    
207
  /// END PROGRAMS //////
208

    
209
  /**
210
   * Every application using the library must implement this interface so that the library can send
211
   * it exceptions that arise. The exceptions may come at any time, for example the library will
212
   * compile its OIT problem only on the first attempt to use the OIT
213
   * Those will mainly be hardware-related: shaders do not compile on particular hardware, the required
214
   * OpenGL ES 3.0 is not supported, etc.
215
   */
216
  public interface ExceptionListener
217
    {
218
    void distortedException(Exception ex);
219
    }
220

    
221
  private static ExceptionListener mListener;
222
  private static Resources mResources;
223

    
224
///////////////////////////////////////////////////////////////////////////////////////////////////
225
// private: hide this from Javadoc
226

    
227
  private DistortedLibrary()
228
    {
229

    
230
    }
231

    
232
///////////////////////////////////////////////////////////////////////////////////////////////////
233

    
234
  private static void createMainProgram()
235
    {
236
    // MAIN PROGRAM ////////////////////////////////////
237
    final InputStream mainVertStream = mResources.openRawResource(R.raw.main_vertex_shader);
238
    final InputStream mainFragStream = mResources.openRawResource(R.raw.main_fragment_shader);
239

    
240
    int numF = FragmentEffect.getNumEnabled();
241
    int numV = VertexEffect.getNumEnabled();
242

    
243
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
244
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
245

    
246
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
247

    
248
    String enabledEffectV= VertexEffect.getGLSL();
249
    String enabledEffectF= FragmentEffect.getGLSL();
250

    
251
    String[] feedback = { "v_Position", "v_endPosition" };
252

    
253
    try
254
      {
255
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
256
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
257
      }
258
    catch(Exception e)
259
      {
260
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
261
      throw new RuntimeException(e.getMessage());
262
      }
263

    
264
    mMainProgramH = mMainProgram.getProgramHandle();
265
    EffectQueue.getUniforms(mMainProgramH,0);
266
    MeshBase.getUniforms(mMainProgramH,0);
267
    mMainTextureH= GLES30.glGetUniformLocation( mMainProgramH, "u_Texture");
268
    mTransformFeedbackH= GLES30.glGetUniformLocation( mMainProgramH, "u_TransformFeedback");
269

    
270
    // BLIT PROGRAM ////////////////////////////////////
271
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
272
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
273

    
274
    try
275
      {
276
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
277
      }
278
    catch(Exception e)
279
      {
280
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
281
      throw new RuntimeException(e.getMessage());
282
      }
283

    
284
    int blitProgramH = mBlitProgram.getProgramHandle();
285
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
286
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
287

    
288
    // BLIT DEPTH PROGRAM ////////////////////////////////////
289
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
290
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
291

    
292
    try
293
      {
294
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
295
      }
296
    catch(Exception e)
297
      {
298
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
299
      throw new RuntimeException(e.getMessage());
300
      }
301

    
302
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
303
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
304
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
305
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
306
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
307
    }
308

    
309
///////////////////////////////////////////////////////////////////////////////////////////////////
310

    
311
  private static void createNormalProgram(Resources resources)
312
    {
313
    // NORMAL PROGRAM //////////////////////////////////////
314
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
315
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
316

    
317
    try
318
      {
319
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
320
      }
321
    catch(Exception e)
322
      {
323
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
324
      throw new RuntimeException(e.getMessage());
325
      }
326

    
327
    int normalProgramH = mNormalProgram.getProgramHandle();
328
    mNormalProjectionH = GLES30.glGetUniformLocation( normalProgramH, "u_Projection");
329
    }
330

    
331
///////////////////////////////////////////////////////////////////////////////////////////////////
332

    
333
  private static void createFullProgram(Resources resources)
334
    {
335
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
336
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
337

    
338
    int numV = VertexEffect.getAllEnabled();
339

    
340
    String fullVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX ) : 0 ) + "\n");
341
    String fullFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " +                                         0   + "\n");
342

    
343
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
344

    
345
    String enabledEffectV= VertexEffect.getAllGLSL();
346
    String enabledEffectF= "{}";
347

    
348
    fullVertHeader += "#define PREAPPLY\n";
349

    
350
    String[] feedback = { "v_Position", "v_endPosition" };
351

    
352
    try
353
      {
354
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
355
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
356
      }
357
    catch(Exception e)
358
      {
359
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
360
      throw new RuntimeException(e.getMessage());
361
      }
362

    
363
    mFullProgramH = mFullProgram.getProgramHandle();
364
    EffectQueue.getUniforms(mFullProgramH,3);
365
    MeshBase.getUniforms(mFullProgramH,3);
366
    }
367

    
368
///////////////////////////////////////////////////////////////////////////////////////////////////
369

    
370
  private static void createOITProgram(Resources resources)
371
    {
372
    // MAIN OIT PROGRAM ////////////////////////////////
373
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
374
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
375

    
376
    int numF = FragmentEffect.getNumEnabled();
377
    int numV = VertexEffect.getNumEnabled();
378

    
379
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") + ("#define OIT\n");
380
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") + ("#define OIT\n");
381

    
382
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
383

    
384
    String enabledEffectV= VertexEffect.getGLSL();
385
    String enabledEffectF= FragmentEffect.getGLSL();
386

    
387
    try
388
      {
389
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
390
                                             enabledEffectV, enabledEffectF, mGLSL, null);
391
      }
392
    catch(Exception e)
393
      {
394
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
395
      throw new RuntimeException(e.getMessage());
396
      }
397

    
398
    mMainOITProgramH = mMainOITProgram.getProgramHandle();
399
    EffectQueue.getUniforms(mMainOITProgramH,1);
400
    MeshBase.getUniforms(mMainOITProgramH,1);
401
    mMainOITTextureH    = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Texture");
402
    mMainOITSizeH       = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Size");
403
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mMainOITProgramH, "u_numRecords");
404

    
405
    // OIT CLEAR PROGRAM ////////////////////////////////////
406
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
407
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
408

    
409
    try
410
      {
411
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
412
      }
413
    catch(Exception e)
414
      {
415
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
416
      throw new RuntimeException(e.getMessage());
417
      }
418

    
419
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
420
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
421
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
422
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
423

    
424
    // OIT BUILD PROGRAM ////////////////////////////////////
425
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
426
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
427

    
428
    try
429
      {
430
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
431
      }
432
    catch(Exception e)
433
      {
434
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
435
      throw new RuntimeException(e.getMessage());
436
      }
437

    
438
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
439
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
440
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
441
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
442
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
443
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
444
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
445

    
446
    // OIT COLLAPSE PROGRAM ///////////////////////////
447
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
448
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
449

    
450
    try
451
      {
452
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
453
      }
454
    catch(Exception e)
455
      {
456
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
457
      throw new RuntimeException(e.getMessage());
458
      }
459

    
460
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
461
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
462
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
463
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
464
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
465

    
466
    // OIT RENDER PROGRAM ///////////////////////////
467
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
468
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
469

    
470
    try
471
      {
472
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
473
      }
474
    catch(Exception e)
475
      {
476
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
477
      throw new RuntimeException(e.getMessage());
478
      }
479

    
480
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
481
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
482
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
483
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
484
    }
485

    
486
///////////////////////////////////////////////////////////////////////////////////////////////////
487

    
488
  private static void displayNormals(float[] projection, MeshBase mesh)
489
    {
490
    if( mNormalProgram==null )
491
      {
492
      try
493
        {
494
        createNormalProgram(mResources);
495
        }
496
      catch(Exception ex)
497
        {
498
        mListener.distortedException(ex);
499
        return;
500
        }
501
      }
502

    
503
    int num = mesh.getNumVertices();
504
    int tfo = mesh.getTFO();
505

    
506
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 1);
507
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
508
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
509
    InternalRenderState.switchOffDrawing();
510
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
511
    InternalRenderState.restoreDrawing();
512
    GLES30.glEndTransformFeedback();
513
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
514
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 0);
515

    
516
    mNormalProgram.useProgram();
517
    GLES30.glUniformMatrix4fv(mNormalProjectionH, 1, false, projection, 0);
518
    mesh.bindTransformAttribs(mNormalProgram);
519
    GLES30.glLineWidth(8.0f);
520
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
521
    }
522

    
523
///////////////////////////////////////////////////////////////////////////////////////////////////
524
/**
525
 * Execute all VertexEffects and adjust all vertices
526
 *
527
 * @y.exclude
528
 */
529
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
530
    {
531
    if( mFullProgram==null )
532
      {
533
      try
534
        {
535
        createFullProgram(mResources);
536
        }
537
      catch(Exception ex)
538
        {
539
        mListener.distortedException(ex);
540
        return;
541
        }
542
      }
543

    
544
    int num = mesh.getNumVertices();
545
    int tfo = mesh.getTFO();
546

    
547
    mFullProgram.useProgram();
548
    mesh.bindVertexAttribs(mFullProgram);
549
    queue.compute(1);
550
    queue.send(0.0f,3);
551
    mesh.send(mFullProgramH,3);
552

    
553
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
554
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
555
    InternalRenderState.switchOffDrawing();
556
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
557
    InternalRenderState.restoreDrawing();
558
    GLES30.glEndTransformFeedback();
559
    mesh.copyTransformToVertex();
560
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
561
    }
562

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

    
565
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
566
    {
567
    if( mMainOITProgram!=null )
568
      {
569
      EffectQueue[] queues = effects.getQueues();
570

    
571
      EffectQueue.compute(queues, currTime);
572
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
573

    
574
      mMainOITProgram.useProgram();
575
      GLES30.glUniform1i(mMainOITTextureH, 0);
576
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
577
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
578
      mesh.bindVertexAttribs(mMainOITProgram);
579
      mesh.send(mMainOITProgramH,1);
580

    
581
      float inflate     = mesh.getInflate();
582
      float distance    = surface.mDistance;
583
      float mipmap      = surface.mMipmap;
584
      float[] projection= surface.mProjectionMatrix;
585

    
586
      EffectQueue.send(queues, distance, mipmap, projection, inflate, 1 );
587
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
588

    
589
      if( mesh.getShowNormals() )
590
        {
591
        mMainProgram.useProgram();
592
        mesh.send(mMainProgramH,0);
593
        EffectQueue.send(queues, distance, mipmap, projection, inflate, 0 );
594
        displayNormals(projection,mesh);
595
        }
596
      }
597
    }
598

    
599
///////////////////////////////////////////////////////////////////////////////////////////////////
600

    
601
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
602
    {
603
    if( mMainProgram!=null )
604
      {
605
      EffectQueue[] queues = effects.getQueues();
606

    
607
      EffectQueue.compute(queues, currTime);
608
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
609

    
610
      mMainProgram.useProgram();
611
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
612
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
613
      mesh.send(mMainProgramH,0);
614

    
615
      float inflate     = mesh.getInflate();
616
      float distance    = surface.mDistance;
617
      float mipmap      = surface.mMipmap;
618
      float[] projection= surface.mProjectionMatrix;
619

    
620
      EffectQueue.send(queues, distance, mipmap, projection, inflate, 0 );
621
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
622

    
623
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
624
      }
625
    }
626

    
627
///////////////////////////////////////////////////////////////////////////////////////////////////
628

    
629
  static void blitPriv(InternalOutputSurface surface)
630
    {
631
    if( mBlitProgram!=null )
632
      {
633
      mBlitProgram.useProgram();
634

    
635
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
636
      GLES30.glUniform1i(mBlitTextureH, 0);
637
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
638
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
639
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
640
      }
641
    }
642

    
643
///////////////////////////////////////////////////////////////////////////////////////////////////
644

    
645
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
646
    {
647
    if( mBlitDepthProgram!=null )
648
      {
649
      mBlitDepthProgram.useProgram();
650

    
651
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
652
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
653
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
654
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
655
      GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
656
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
657
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
658
      }
659
    }
660

    
661
///////////////////////////////////////////////////////////////////////////////////////////////////
662
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
663

    
664
  private static int printPreviousBuffer()
665
    {
666
    int counter = 0;
667

    
668
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
669
                                                                GLES30.GL_MAP_READ_BIT);
670
    if( atomicBuf!=null )
671
      {
672
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
673
      counter = atomicIntBuf.get(0);
674
      }
675
    else
676
      {
677
      Log.e("effects", "print: failed to map atomic buffer");
678
      }
679

    
680
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
681

    
682
    return counter;
683
    }
684

    
685
///////////////////////////////////////////////////////////////////////////////////////////////////
686

    
687
  private static void zeroBuffer()
688
    {
689
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
690
                                                                GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
691
    if( atomicBuf!=null )
692
      {
693
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
694
      atomicIntBuf.put(0,0);
695
      }
696
    else
697
      {
698
      Log.e("effects", "zero: failed to map atomic buffer");
699
      }
700

    
701
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
702
    }
703

    
704
///////////////////////////////////////////////////////////////////////////////////////////////////
705
// reset atomic counter to 0
706

    
707
  static int zeroOutAtomic()
708
    {
709
    int counter = 0;
710

    
711
    if( mAtomicCounter==null )
712
      {
713
      mAtomicCounter = new int[mFBOQueueSize];
714

    
715
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
716

    
717
      for(int i=0; i<mFBOQueueSize; i++)
718
        {
719
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
720
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
721
        zeroBuffer();
722
        }
723
      }
724

    
725
    // reading the value of the buffer on every frame would slow down rendering by
726
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
727
    if( mCurrBuffer==0 )
728
      {
729
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
730
      counter = printPreviousBuffer();
731
      }
732

    
733
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
734

    
735
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
736
    zeroBuffer();
737

    
738
    return counter;
739
    }
740

    
741
///////////////////////////////////////////////////////////////////////////////////////////////////
742
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
743

    
744
  static void oitClear(InternalOutputSurface surface, int counter)
745
    {
746
    if( mOITClearProgram==null )
747
      {
748
      if( mGLSL>=310 && !mOITCompilationAttempted )
749
        {
750
        mOITCompilationAttempted = true;
751

    
752
        try
753
          {
754
          createOITProgram(mResources);
755
          }
756
        catch(Exception ex)
757
          {
758
          mListener.distortedException(ex);
759
          return;
760
          }
761
        }
762
      else
763
        {
764
        return;
765
        }
766
      }
767

    
768
    if( mLinkedListSSBO[0]<0 )
769
      {
770
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
771

    
772
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
773
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
774
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
775
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
776

    
777
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
778
      }
779

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

    
784
    if( overflow>1.0f )
785
      {
786
      mBufferSize *= (int)(overflow+1.0f);
787
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
788
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
789
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
790
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
791
      }
792

    
793
    mOITClearProgram.useProgram();
794

    
795
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
796
    GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
797
    GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
798
    GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
799
    GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
800
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
801
    }
802

    
803
///////////////////////////////////////////////////////////////////////////////////////////////////
804
// Pass2 of the OIT algorithm - build per-pixel linked lists.
805

    
806
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
807
    {
808
    if( mOITBuildProgram!=null )
809
      {
810
      mOITBuildProgram.useProgram();
811

    
812
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
813
      GLES30.glUniform1i(mOITBuildTextureH, 0);
814
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
815
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
816
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
817
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
818
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
819
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
820
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
821
      }
822
    }
823

    
824
///////////////////////////////////////////////////////////////////////////////////////////////////
825
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
826

    
827
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
828
    {
829
    if( mOITCollapseProgram!=null )
830
      {
831
      mOITCollapseProgram.useProgram();
832

    
833
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
834
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
835
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
836
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
837
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
838
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
839
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
840
      }
841
    }
842

    
843
///////////////////////////////////////////////////////////////////////////////////////////////////
844
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
845

    
846
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
847
    {
848
    if( mOITRenderProgram!=null )
849
      {
850
      mOITRenderProgram.useProgram();
851

    
852
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
853
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
854
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
855
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
856
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
857
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
858
      }
859
    }
860

    
861
///////////////////////////////////////////////////////////////////////////////////////////////////
862

    
863
  static void setSSBOSize(float size)
864
    {
865
    mBufferSize = size;
866
    }
867

    
868
///////////////////////////////////////////////////////////////////////////////////////////////////
869

    
870
  static int getQueueSize()
871
    {
872
    return mFBOQueueSize;
873
    }
874

    
875
///////////////////////////////////////////////////////////////////////////////////////////////////
876
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
877
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
878

    
879
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
880
    {
881
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
882
    String version = GLES30.glGetString(GLES30.GL_VERSION);
883
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
884

    
885
    mFBOQueueSize = 1;
886

    
887
    if( vendor.contains("ARM") )
888
      {
889
      try
890
        {
891
        String regex = ".*r(\\d+)p\\d.*";
892
        Pattern pattern = Pattern.compile(regex);
893
        Matcher matcher = pattern.matcher(version);
894

    
895
        if( matcher.find() )
896
          {
897
          String driverVersion = matcher.group(1);
898

    
899
          if( driverVersion!=null )
900
            {
901
            int drvVersion = Integer.parseInt(driverVersion);
902

    
903
            if( drvVersion<22 )
904
              {
905
              Log.e("DISTORTED", "You are running this on a ARM Mali driver r"+driverVersion+".\n" +
906
                    "This is a buggy driver, please update to r22. Inserting workaround which uses a lot of memory.");
907

    
908
              mFBOQueueSize = queueSize;
909
              }
910
            }
911
          }
912
        }
913
      catch(Exception ex)
914
        {
915
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
916
        }
917
      }
918
    else if( vendor.contains("Imagination") )
919
      {
920
      if( renderer.contains("GE8") )
921
        {
922
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
923
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
924
        }
925
      }
926
    }
927

    
928
///////////////////////////////////////////////////////////////////////////////////////////////////
929
/**
930
 * Return OpenGL ES version supported by the hardware we are running on.
931
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
932
 * or 200 (OpenGL ES 2.0)
933
 */
934
  public static int getGLSL()
935
    {
936
    return mGLSL;
937
    }
938

    
939
///////////////////////////////////////////////////////////////////////////////////////////////////
940
/**
941
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
942
 * I.e. best called from GLSurfaceView.Renderer.onSurfaceCreated().
943
 * <p>
944
 * Needs to be called from a thread holding the OpenGL context.
945
 *
946
 * @param context  Context of the App using the library - used to open up Resources and read Shader code.
947
 * @param listener The library will send all (asynchronous!) exceptions there.
948
 */
949
  public static void onSurfaceCreated(final Context context, final ExceptionListener listener)
950
    {
951
    onSurfaceCreated(context,listener,4);
952
    }
953

    
954
///////////////////////////////////////////////////////////////////////////////////////////////////
955
/**
956
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
957
 * I.e. best called from GLSurfaceView.Renderer.onSurfaceCreated().
958
 * <p>
959
 * Needs to be called from a thread holding the OpenGL context.
960
 *   
961
 * @param context   Context of the App using the library - used to open up Resources and read Shader code.
962
 * @param listener  The library will send all (asynchronous!) exceptions there.
963
 * @param queueSize the size of the FBO queue, a workaround for the bug on Mali drivers. Use a small integer - 1,...,4
964
 */
965
  public static void onSurfaceCreated(final Context context, final ExceptionListener listener, int queueSize)
966
    {
967
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
968
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
969

    
970
    int glESversion = configurationInfo.reqGlEsVersion;
971
    int major = glESversion >> 16;
972
    int minor = glESversion & 0xff;
973

    
974
    mListener = listener;
975

    
976
    if( major< 3 )
977
      {
978
      mGLSL = 100*major + 10*minor;
979
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
980
      mListener.distortedException(ex);
981
      }
982
    else
983
      {
984
      mGLSL = (major==3 && minor==0) ? 300 : 310;
985
      }
986

    
987
    int[] maxTextureSize = new int[1];
988
    GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0);
989
    mMaxTextureSize = maxTextureSize[0];
990

    
991
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+major+"."+minor);
992
    mGLSL_VERSION = "#version "+mGLSL+" es\n";
993

    
994
    InternalStackFrameList.setInitialized(true);
995
    mOITCompilationAttempted = false;
996

    
997
    detectBuggyDriversAndSetQueueSize(queueSize);
998
    EffectMessageSender.startSending();
999

    
1000
    mResources = context.getResources();
1001

    
1002
    try
1003
      {
1004
      createMainProgram();
1005
      }
1006
    catch(Exception ex)
1007
      {
1008
      mListener.distortedException(ex);
1009
      }
1010

    
1011
    try
1012
      {
1013
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1014
      }
1015
    catch(Exception ex)
1016
      {
1017
      mListener.distortedException(ex);
1018
      }
1019

    
1020
    try
1021
      {
1022
      PostprocessEffect.createPrograms(mGLSL);
1023
      }
1024
    catch(Exception ex)
1025
      {
1026
      mListener.distortedException(ex);
1027
      }
1028
    }
1029

    
1030
///////////////////////////////////////////////////////////////////////////////////////////////////
1031
/**
1032
 * Call this so that the Library can initialize its internal data structures.
1033
 * Must be called from Activity.onCreate().
1034
 */
1035
  public static void onCreate()
1036
    {
1037
    onCreate(0);
1038
    }
1039

    
1040
///////////////////////////////////////////////////////////////////////////////////////////////////
1041
/**
1042
 * Call this so that the Library can initialize its internal data structures.
1043
 * Must be called from Activity.onCreate().
1044
 *
1045
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1046
 *           tell between Activities in case you're going to be using it from more than one.
1047
 */
1048
  public static void onCreate(long id)
1049
    {
1050
    InternalStackFrameList.onCreate(id);
1051
    }
1052

    
1053
///////////////////////////////////////////////////////////////////////////////////////////////////
1054
/**
1055
 * Call this so that the Library can resume its operations.
1056
 * Must be called from Activity.onResume().
1057
 */
1058
  public static void onResume()
1059
    {
1060
    onCreate(0);
1061
    }
1062

    
1063
///////////////////////////////////////////////////////////////////////////////////////////////////
1064
/**
1065
 * Call this so that the Library can resume its operations.
1066
 * Must be called from Activity.onResume().
1067
 *
1068
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1069
 *           tell between Activities in case you're going to be using it from more than one.
1070
 */
1071
  public static void onResume(long id)
1072
    {
1073
    InternalStackFrameList.onResume(id);
1074
    }
1075

    
1076
///////////////////////////////////////////////////////////////////////////////////////////////////
1077
/**
1078
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1079
 * Must be called from Activity.onPause().
1080
 */
1081
  public static void onPause()
1082
    {
1083
    onPause(0);
1084
    }
1085

    
1086
///////////////////////////////////////////////////////////////////////////////////////////////////
1087
/**
1088
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1089
 * Must be called from Activity.onPause().
1090
 *
1091
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1092
 *           tell between Activities in case you're going to be using it from more than one.
1093
 */
1094
  public static void onPause(long id)
1095
    {
1096
    InternalStackFrameList.onPause(id);
1097
    Dynamic.onPause();  // common for all frames
1098

    
1099
    mLinkedListSSBO[0]= -1;
1100
    mAtomicCounter = null;
1101

    
1102
    mNormalProgram     = null;
1103
    mMainOITProgram    = null;
1104
    mMainProgram       = null;
1105
    mFullProgram       = null;
1106
    mOITClearProgram   = null;
1107
    mOITBuildProgram   = null;
1108
    mOITCollapseProgram= null;
1109
    mOITRenderProgram  = null;
1110
    mBlitDepthProgram  = null;
1111
    mBlitProgram       = null;
1112
    }
1113

    
1114
///////////////////////////////////////////////////////////////////////////////////////////////////
1115
/**
1116
 * Call this so that the Library can release its internal data structures.
1117
 * Must be called from Activity.onDestroy().
1118
 */
1119
  public static void onDestroy()
1120
    {
1121
    onDestroy(0);
1122
    }
1123

    
1124
///////////////////////////////////////////////////////////////////////////////////////////////////
1125
/**
1126
 * Call this so that the Library can release its internal data structures.
1127
 * Must be called from Activity.onDestroy().
1128
 *
1129
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1130
 *           tell between Activities in case you're going to be using it from more than one.
1131
 */
1132
  public static void onDestroy(long id)
1133
    {
1134
    if( InternalStackFrameList.isInitialized() )
1135
      {
1136
      InternalStackFrameList.onDestroy(id);
1137

    
1138
      InternalOutputSurface.onDestroy(); // those three really destroy
1139
      Effect.onDestroy();                // static data that does not
1140
      DeferredJobs.onDestroy();          // need to be part of a frame
1141

    
1142
      mOITCompilationAttempted = false;
1143
      }
1144
    }
1145

    
1146
///////////////////////////////////////////////////////////////////////////////////////////////////
1147
/**
1148
 * Return the maximum size of the texture supported by the driver.
1149
 */
1150
  public static int getMaxTextureSize()
1151
    {
1152
    return mMaxTextureSize;
1153
    }
1154

    
1155
///////////////////////////////////////////////////////////////////////////////////////////////////
1156
/**
1157
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1158
 * single (InputSurface,MeshBase) combo.
1159
 *
1160
 * @param type {@link EffectType}
1161
 * @return The maximum number of effects of a given type.
1162
 */
1163
  @SuppressWarnings("unused")
1164
  public static int getMax(EffectType type)
1165
    {
1166
    return EffectQueue.getMax(type.ordinal());
1167
    }
1168

    
1169
///////////////////////////////////////////////////////////////////////////////////////////////////
1170
/**
1171
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1172
 * This can fail if:
1173
 * <ul>
1174
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1175
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1176
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onSurfaceCreated}. After this
1177
 *     time only decreasing the value of 'max' is permitted.
1178
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1179
 * </ul>
1180
 *
1181
 * @param type {@link EffectType}
1182
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1183
 *            than Byte.MAX_VALUE
1184
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1185
 */
1186
  @SuppressWarnings("unused")
1187
  public static boolean setMax(EffectType type, int max)
1188
    {
1189
    return EffectQueue.setMax(type.ordinal(),max);
1190
    }
1191
  }
(3-3/16)