Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 9f9924f8

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

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

    
120
  private static boolean mInitialized=false;
121

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
208
  /// END PROGRAMS //////
209

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

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

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

    
228
  private DistortedLibrary()
229
    {
230

    
231
    }
232

    
233
///////////////////////////////////////////////////////////////////////////////////////////////////
234

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
310
///////////////////////////////////////////////////////////////////////////////////////////////////
311

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

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

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

    
332
///////////////////////////////////////////////////////////////////////////////////////////////////
333

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

    
339
    int numV = VertexEffect.getAllEnabled();
340

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

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

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

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

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

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

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

    
369
///////////////////////////////////////////////////////////////////////////////////////////////////
370

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
487
///////////////////////////////////////////////////////////////////////////////////////////////////
488

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

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

    
507
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 1);
508
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
509
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
510
    InternalRenderState.switchOffDrawing();
511
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
512
    InternalRenderState.restoreDrawing();
513
    GLES30.glEndTransformFeedback();
514
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 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
 * Have we called onCreate yet, ie have we initialized the library?
942
 * @return <code>true</code> if the library is initialized and ready for action.
943
 */
944
  public static boolean isInitialized()
945
    {
946
    return mInitialized;
947
    }
948

    
949
///////////////////////////////////////////////////////////////////////////////////////////////////
950
/**
951
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
952
 * I.e. best called from GLSurfaceView.onCreate().
953
 * <p>
954
 * Needs to be called from a thread holding the OpenGL context.
955
 *
956
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
957
 * @param listener The library will send all (asynchronous!) exceptions there.
958
 */
959
  public static void onCreate(final Context context, final ExceptionListener listener)
960
    {
961
    onCreate(context,listener,4);
962
    }
963

    
964
///////////////////////////////////////////////////////////////////////////////////////////////////
965
/**
966
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
967
 * I.e. best called from GLSurfaceView.onCreate().
968
 * <p>
969
 * Needs to be called from a thread holding the OpenGL context.
970
 *   
971
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
972
 * @param listener The library will send all (asynchronous!) exceptions there.
973
 * @param queueSize the size of the FBO queue, a workaround for the bug on Mali drivers.
974
 */
975
  public static void onCreate(final Context context, final ExceptionListener listener, int queueSize)
976
    {
977
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
978
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
979

    
980
    int glESversion = configurationInfo.reqGlEsVersion;
981
    int major = glESversion >> 16;
982
    int minor = glESversion & 0xff;
983

    
984
    mListener = listener;
985

    
986
    if( major< 3 )
987
      {
988
      mGLSL = 100*major + 10*minor;
989
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
990
      mListener.distortedException(ex);
991
      }
992
    else
993
      {
994
      mGLSL = (major==3 && minor==0) ? 300 : 310;
995
      }
996

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

    
1000
    mInitialized = true;
1001
    mOITCompilationAttempted = false;
1002

    
1003
    detectBuggyDriversAndSetQueueSize(queueSize);
1004

    
1005
    EffectMessageSender.startSending();
1006

    
1007
    mResources = context.getResources();
1008

    
1009
    try
1010
      {
1011
      createMainProgram();
1012
      }
1013
    catch(Exception ex)
1014
      {
1015
      mListener.distortedException(ex);
1016
      }
1017

    
1018
    try
1019
      {
1020
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1021
      }
1022
    catch(Exception ex)
1023
      {
1024
      mListener.distortedException(ex);
1025
      }
1026

    
1027
    try
1028
      {
1029
      PostprocessEffect.createPrograms(mGLSL);
1030
      }
1031
    catch(Exception ex)
1032
      {
1033
      mListener.distortedException(ex);
1034
      }
1035
    }
1036

    
1037
///////////////////////////////////////////////////////////////////////////////////////////////////
1038
/**
1039
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1040
 * Must be called from Activity.onPause().
1041
 */
1042
  public static void onPause()
1043
    {
1044
    InternalObject.onPause();
1045
    Dynamic.onPause();
1046
    mLinkedListSSBO[0]= -1;
1047
    mAtomicCounter = null;
1048

    
1049
    mFullProgram        = null;
1050
    mNormalProgram      = null;
1051
    mOITRenderProgram   = null;
1052
    mOITCollapseProgram = null;
1053
    mOITBuildProgram    = null;
1054
    mOITClearProgram    = null;
1055
    }
1056

    
1057
///////////////////////////////////////////////////////////////////////////////////////////////////
1058
/**
1059
 * Call this so that the Library can release its internal data structures.
1060
 * Must be called from Activity.onDestroy(). 
1061
 */
1062
  public static void onDestroy()
1063
    {
1064
    InternalObject.onDestroy();
1065
    InternalNodeData.onDestroy();
1066
    InternalMaster.onDestroy();
1067
    InternalOutputSurface.onDestroy();
1068
    DistortedEffects.onDestroy();
1069
    EffectQueue.onDestroy();
1070
    Effect.onDestroy();
1071
    DeferredJobs.onDestroy();
1072
    EffectMessageSender.stopSending();
1073

    
1074
    mInitialized = false;
1075
    mOITCompilationAttempted = false;
1076

    
1077
    mNormalProgram     = null;
1078
    mMainOITProgram    = null;
1079
    mMainProgram       = null;
1080
    mFullProgram       = null;
1081
    mOITClearProgram   = null;
1082
    mOITBuildProgram   = null;
1083
    mOITCollapseProgram= null;
1084
    mOITRenderProgram  = null;
1085
    mBlitDepthProgram  = null;
1086
    mBlitProgram       = null;
1087
    }
1088

    
1089
///////////////////////////////////////////////////////////////////////////////////////////////////
1090
/**
1091
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1092
 * single (InputSurface,MeshBase) combo.
1093
 *
1094
 * @param type {@link EffectType}
1095
 * @return The maximum number of effects of a given type.
1096
 */
1097
  @SuppressWarnings("unused")
1098
  public static int getMax(EffectType type)
1099
    {
1100
    return EffectQueue.getMax(type.ordinal());
1101
    }
1102

    
1103
///////////////////////////////////////////////////////////////////////////////////////////////////
1104
/**
1105
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1106
 * This can fail if:
1107
 * <ul>
1108
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1109
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1110
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onCreate}. After this
1111
 *     time only decreasing the value of 'max' is permitted.
1112
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1113
 * </ul>
1114
 *
1115
 * @param type {@link EffectType}
1116
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1117
 *            than Byte.MAX_VALUE
1118
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1119
 */
1120
  @SuppressWarnings("unused")
1121
  public static boolean setMax(EffectType type, int max)
1122
    {
1123
    return EffectQueue.setMax(type.ordinal(),max);
1124
    }
1125
  }
(3-3/14)