Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 3bbe4d67

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;
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

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

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

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

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

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

    
562
///////////////////////////////////////////////////////////////////////////////////////////////////
563

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

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

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

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

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

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

    
598
///////////////////////////////////////////////////////////////////////////////////////////////////
599

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

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

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

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

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

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

    
626
///////////////////////////////////////////////////////////////////////////////////////////////////
627

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

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

    
642
///////////////////////////////////////////////////////////////////////////////////////////////////
643

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

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

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

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

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

    
679
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
680

    
681
    return counter;
682
    }
683

    
684
///////////////////////////////////////////////////////////////////////////////////////////////////
685

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

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

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

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

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

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

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

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

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

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

    
737
    return counter;
738
    }
739

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

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

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

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

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

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

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

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

    
792
    mOITClearProgram.useProgram();
793

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

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

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

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

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

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

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

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

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

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

    
860
///////////////////////////////////////////////////////////////////////////////////////////////////
861

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

    
867
///////////////////////////////////////////////////////////////////////////////////////////////////
868

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

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

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

    
884
    mFBOQueueSize = 1;
885

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

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

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

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

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

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

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

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

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

    
973
    mListener = listener;
974

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

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

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

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

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

    
999
    mResources = context.getResources();
1000

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1141
      mOITCompilationAttempted = false;
1142
      }
1143
    }
1144

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

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

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