Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ b7074bc6

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.mesh.MeshBase;
39
import org.distorted.library.message.EffectMessageSender;
40
import org.distorted.library.program.DistortedProgram;
41
import org.distorted.library.program.VertexCompilationException;
42

    
43
import java.io.InputStream;
44
import java.nio.ByteBuffer;
45
import java.nio.ByteOrder;
46
import java.nio.FloatBuffer;
47
import java.nio.IntBuffer;
48

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

    
98
  /**
99
   * Work around bugs in ARM Mali driver by, instead to a single FBO, rendering to a circular queue
100
   * of FBO_QUEUE_SIZE FBOs. (otherwise we sometimes get a 'full pipeline flush' and the end result
101
   * might be missing part of the Objects)
102
   *
103
   * This bug only exists on Mali driver r12.
104
   *
105
   * https://community.arm.com/graphics/f/discussions/10285/opengl-es-3-1-on-mali-t880-flashes
106
   */
107
  static final int FBO_QUEUE_SIZE = 4;
108

    
109
  private static boolean mInitialized=false;
110

    
111
  //////////////////////////////////////////////////////////////////////////////////////////////
112
  /// MAIN PROGRAM ///
113
  private static DistortedProgram mMainProgram;
114
  private static int mMainTextureH;
115

    
116
  /// NORMAL PROGRAM /////
117
  private static DistortedProgram mNormalProgram;
118
  private static int mNormalMVPMatrixH;
119

    
120
  /// MAIN OIT PROGRAM ///
121
  private static DistortedProgram mMainOITProgram;
122
  private static int mMainOITTextureH;
123
  private static int mMainOITSizeH;
124
  private static int mMainOITNumRecordsH;
125

    
126
  /// BLIT PROGRAM ///
127
  private static DistortedProgram mBlitProgram;
128
  private static int mBlitTextureH;
129
  private static int mBlitDepthH;
130
  private static final FloatBuffer mQuadPositions;
131

    
132
  static
133
    {
134
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
135
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
136
    mQuadPositions.put(positionData).position(0);
137
    }
138

    
139
  /// BLIT DEPTH PROGRAM ///
140
  private static DistortedProgram mBlitDepthProgram;
141
  private static int mBlitDepthTextureH;
142
  private static int mBlitDepthDepthTextureH;
143
  private static int mBlitDepthDepthH;
144
  private static int mBlitDepthTexCorrH;
145

    
146
  /// OIT SSBO BUFFER ///
147
  private static int[] mLinkedListSSBO = new int[1];
148
  private static int[] mAtomicCounter = new int[DistortedLibrary.FBO_QUEUE_SIZE];
149
  private static int   mCurrBuffer;
150

    
151
  static
152
    {
153
    mLinkedListSSBO[0]= -1;
154
    mCurrBuffer       =  0;
155

    
156
    for(int i = 0; i< DistortedLibrary.FBO_QUEUE_SIZE; i++)  mAtomicCounter[i] = -1;
157
    }
158

    
159
  ///////////////////////////////////////////////////////////////
160
  // meaning: allocate 1.0 screenful of places for transparent
161
  // fragments in the SSBO backing up the OIT render method.
162
  private static float mBufferSize=1.0f;
163

    
164
  /// OIT CLEAR PROGRAM ///
165
  private static DistortedProgram mOITClearProgram;
166
  private static int mOITClearDepthH;
167
  private static int mOITClearTexCorrH;
168
  private static int mOITClearSizeH;
169

    
170
  /// OIT BUILD PROGRAM ///
171
  private static DistortedProgram mOITBuildProgram;
172
  private static int mOITBuildTextureH;
173
  private static int mOITBuildDepthTextureH;
174
  private static int mOITBuildDepthH;
175
  private static int mOITBuildTexCorrH;
176
  private static int mOITBuildSizeH;
177
  private static int mOITBuildNumRecordsH;
178

    
179
  /// OIT COLLAPSE PROGRAM ///
180
  private static DistortedProgram mOITCollapseProgram;
181
  private static int mOITCollapseDepthTextureH;
182
  private static int mOITCollapseDepthH;
183
  private static int mOITCollapseTexCorrH;
184
  private static int mOITCollapseSizeH;
185

    
186
  /// OIT RENDER PROGRAM ///
187
  private static DistortedProgram mOITRenderProgram;
188
  private static int mOITRenderDepthH;
189
  private static int mOITRenderTexCorrH;
190
  private static int mOITRenderSizeH;
191

    
192
  /// END PROGRAMS //////
193

    
194
///////////////////////////////////////////////////////////////////////////////////////////////////
195
// private: hide this from Javadoc
196

    
197
  private DistortedLibrary()
198
    {
199

    
200
    }
201

    
202
///////////////////////////////////////////////////////////////////////////////////////////////////
203

    
204
  private static void createPrograms(Resources resources)
205
    {
206
    // MAIN PROGRAM ////////////////////////////////////
207
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
208
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
209

    
210
    int numF = FragmentEffect.getNumEnabled();
211
    int numV = VertexEffect.getNumEnabled();
212

    
213
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
214
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
215
    String enabledEffectV= VertexEffect.getGLSL();
216
    String enabledEffectF= FragmentEffect.getGLSL();
217

    
218
    String[] feedback = { "v_Position", "v_endPosition" };
219

    
220
    try
221
      {
222
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
223
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
224
      }
225
    catch(Exception e)
226
      {
227
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
228
      throw new RuntimeException(e.getMessage());
229
      }
230

    
231
    int mainProgramH = mMainProgram.getProgramHandle();
232
    EffectQueue.getUniforms(mainProgramH,0);
233
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
234

    
235
    // BLIT PROGRAM ////////////////////////////////////
236
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
237
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
238

    
239
    try
240
      {
241
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
242
      }
243
    catch(Exception e)
244
      {
245
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
246
      throw new RuntimeException(e.getMessage());
247
      }
248

    
249
    int blitProgramH = mBlitProgram.getProgramHandle();
250
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
251
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
252

    
253
    // BLIT DEPTH PROGRAM ////////////////////////////////////
254
    final InputStream blitDepthVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
255
    final InputStream blitDepthFragStream = resources.openRawResource(R.raw.blit_depth_fragment_shader);
256

    
257
    try
258
      {
259
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
260
      }
261
    catch(Exception e)
262
      {
263
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
264
      throw new RuntimeException(e.getMessage());
265
      }
266

    
267
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
268
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
269
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
270
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
271
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
272

    
273
    // NORMAL PROGRAM //////////////////////////////////////
274
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
275
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
276

    
277
    try
278
      {
279
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
280
      }
281
    catch(Exception e)
282
      {
283
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
284
      throw new RuntimeException(e.getMessage());
285
      }
286

    
287
    int normalProgramH = mNormalProgram.getProgramHandle();
288
    mNormalMVPMatrixH  = GLES30.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
289
    }
290

    
291
///////////////////////////////////////////////////////////////////////////////////////////////////
292

    
293
  private static void createProgramsOIT(Resources resources)
294
    {
295
    // MAIN OIT PROGRAM ////////////////////////////////
296
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
297
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
298

    
299
    int numF = FragmentEffect.getNumEnabled();
300
    int numV = VertexEffect.getNumEnabled();
301

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

    
305
    String enabledEffectV= VertexEffect.getGLSL();
306
    String enabledEffectF= FragmentEffect.getGLSL();
307

    
308
    try
309
      {
310
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
311
                                             enabledEffectV, enabledEffectF, mGLSL, null);
312
      }
313
    catch(Exception e)
314
      {
315
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
316
      throw new RuntimeException(e.getMessage());
317
      }
318

    
319
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
320
    EffectQueue.getUniforms(mainOITProgramH,1);
321
    mMainOITTextureH    = GLES30.glGetUniformLocation( mainOITProgramH, "u_Texture");
322
    mMainOITSizeH       = GLES30.glGetUniformLocation( mainOITProgramH, "u_Size");
323
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mainOITProgramH, "u_numRecords");
324

    
325
    // OIT CLEAR PROGRAM ////////////////////////////////////
326
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
327
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
328

    
329
    try
330
      {
331
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
332
      }
333
    catch(Exception e)
334
      {
335
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
336
      throw new RuntimeException(e.getMessage());
337
      }
338

    
339
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
340
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
341
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
342
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
343

    
344
    // OIT BUILD PROGRAM ////////////////////////////////////
345
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
346
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
347

    
348
    try
349
      {
350
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
351
      }
352
    catch(Exception e)
353
      {
354
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
355
      throw new RuntimeException(e.getMessage());
356
      }
357

    
358
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
359
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
360
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
361
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
362
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
363
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
364
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
365

    
366
    // OIT COLLAPSE PROGRAM ///////////////////////////
367
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
368
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
369

    
370
    try
371
      {
372
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
373
      }
374
    catch(Exception e)
375
      {
376
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
377
      throw new RuntimeException(e.getMessage());
378
      }
379

    
380
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
381
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
382
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
383
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
384
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
385

    
386
    // OIT RENDER PROGRAM ///////////////////////////
387
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
388
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
389

    
390
    try
391
      {
392
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
393
      }
394
    catch(Exception e)
395
      {
396
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
397
      throw new RuntimeException(e.getMessage());
398
      }
399

    
400
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
401
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
402
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
403
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
404
    }
405

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

    
408
  private static void displayNormals(EffectQueue[] queues, MeshBase mesh)
409
    {
410
    int num = mesh.getNumVertices();
411
    int tfo = mesh.getTFO();
412

    
413
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
414
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
415
    InternalRenderState.switchOffDrawing();
416
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
417
    InternalRenderState.restoreDrawing();
418
    GLES30.glEndTransformFeedback();
419
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
420

    
421
    DistortedLibrary.mNormalProgram.useProgram();
422
    GLES30.glUniformMatrix4fv(DistortedLibrary.mNormalMVPMatrixH, 1, false, EffectQueue.getMVP(queues) , 0);
423
    mesh.bindTransformAttribs(DistortedLibrary.mNormalProgram);
424
    GLES30.glLineWidth(8.0f);
425
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
426
    }
427

    
428
///////////////////////////////////////////////////////////////////////////////////////////////////
429

    
430
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
431
    {
432
    EffectQueue[] queues = effects.getQueues();
433

    
434
    EffectQueue.compute(queues, currTime);
435
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
436

    
437
    DistortedLibrary.mMainOITProgram.useProgram();
438
    GLES30.glUniform1i(DistortedLibrary.mMainOITTextureH, 0);
439
    GLES30.glUniform2ui(DistortedLibrary.mMainOITSizeH, surface.mWidth, surface.mHeight);
440
    GLES30.glUniform1ui(DistortedLibrary.mMainOITNumRecordsH, (int)(DistortedLibrary.mBufferSize*surface.mWidth*surface.mHeight) );
441
    mesh.bindVertexAttribs(DistortedLibrary.mMainOITProgram);
442

    
443
    float inflate     = mesh.getInflate();
444
    float distance    = surface.mDistance;
445
    float mipmap      = surface.mMipmap;
446
    float[] projection= surface.mProjectionMatrix;
447

    
448
    EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 1 );
449
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
450

    
451
    if( mesh.getShowNormals() )
452
      {
453
      DistortedLibrary.mMainProgram.useProgram();
454
      EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
455
      displayNormals(queues,mesh);
456
      }
457
    }
458

    
459
///////////////////////////////////////////////////////////////////////////////////////////////////
460

    
461
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
462
    {
463
    EffectQueue[] queues = effects.getQueues();
464

    
465
    EffectQueue.compute(queues, currTime);
466
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
467

    
468
    DistortedLibrary.mMainProgram.useProgram();
469
    GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
470
    mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
471

    
472
    float inflate     = mesh.getInflate();
473
    float distance    = surface.mDistance;
474
    float mipmap      = surface.mMipmap;
475
    float[] projection= surface.mProjectionMatrix;
476

    
477
    EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
478
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
479

    
480
    if( mesh.getShowNormals() ) displayNormals(queues,mesh);
481
    }
482

    
483
///////////////////////////////////////////////////////////////////////////////////////////////////
484

    
485
  static void blitPriv(InternalOutputSurface surface)
486
    {
487
    mBlitProgram.useProgram();
488

    
489
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
490
    GLES30.glUniform1i(mBlitTextureH, 0);
491
    GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
492
    GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
493
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
494
    }
495

    
496
///////////////////////////////////////////////////////////////////////////////////////////////////
497

    
498
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
499
    {
500
    mBlitDepthProgram.useProgram();
501

    
502
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
503
    GLES30.glUniform1i(mBlitDepthTextureH, 0);
504
    GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
505
    GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
506
    GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
507
    GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
508
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
509
    }
510

    
511
///////////////////////////////////////////////////////////////////////////////////////////////////
512
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
513

    
514
  private static int printPreviousBuffer()
515
    {
516
    int counter = 0;
517

    
518
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
519
                                                                GLES30.GL_MAP_READ_BIT);
520
    if( atomicBuf!=null )
521
      {
522
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
523
      counter = atomicIntBuf.get(0);
524
      }
525
    else
526
      {
527
      Log.e("effects", "print: failed to map atomic buffer");
528
      }
529

    
530
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
531

    
532
    return counter;
533
    }
534

    
535
///////////////////////////////////////////////////////////////////////////////////////////////////
536

    
537
  private static void zeroBuffer()
538
    {
539
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
540
        GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
541
    if( atomicBuf!=null )
542
      {
543
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
544
      atomicIntBuf.put(0,0);
545
      }
546
    else
547
      {
548
      Log.e("effects", "zero: failed to map atomic buffer");
549
      }
550

    
551
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
552
    }
553

    
554
///////////////////////////////////////////////////////////////////////////////////////////////////
555
// reset atomic counter to 0
556

    
557
  static int zeroOutAtomic()
558
    {
559
    int counter = 0;
560

    
561
    if( mAtomicCounter[0]<0 )
562
      {
563
      GLES30.glGenBuffers(DistortedLibrary.FBO_QUEUE_SIZE,mAtomicCounter,0);
564

    
565
      for(int i = 0; i< DistortedLibrary.FBO_QUEUE_SIZE; i++)
566
        {
567
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
568
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
569
        zeroBuffer();
570
        }
571
      }
572

    
573
    // reading the value of the buffer on every frame would slow down rendering by
574
    // dialog_about 3%; doing it only once every 5 frames affects speed by less than 1%.
575
    if( mCurrBuffer==0 )
576
      {
577
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
578
      counter = printPreviousBuffer();
579
      }
580

    
581
    if( ++mCurrBuffer>= DistortedLibrary.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
582

    
583
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
584
    zeroBuffer();
585

    
586
    return counter;
587
    }
588

    
589
///////////////////////////////////////////////////////////////////////////////////////////////////
590
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
591

    
592
  static void oitClear(InternalOutputSurface surface, int counter)
593
    {
594
    if( mLinkedListSSBO[0]<0 )
595
      {
596
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
597

    
598
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
599
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
600
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
601
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
602

    
603
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
604
      }
605

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

    
610
    if( overflow>1.0f )
611
      {
612
      //android.util.Log.e("effects", "previous frame rendered "+counter+
613
      //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
614

    
615
      mBufferSize *= (int)(overflow+1.0f);
616
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
617
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
618
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
619
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
620
      }
621

    
622
    mOITClearProgram.useProgram();
623

    
624
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
625
    GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
626
    GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
627
    GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
628
    GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
629
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
630
    }
631

    
632
///////////////////////////////////////////////////////////////////////////////////////////////////
633
// Pass2 of the OIT algorithm - build per-pixel linked lists.
634

    
635
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
636
    {
637
    mOITBuildProgram.useProgram();
638

    
639
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
640
    GLES30.glUniform1i(mOITBuildTextureH, 0);
641
    GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
642
    GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
643
    GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
644
    GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
645
    GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
646
    GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
647
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
648
    }
649

    
650
///////////////////////////////////////////////////////////////////////////////////////////////////
651
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
652

    
653
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
654
    {
655
    mOITCollapseProgram.useProgram();
656

    
657
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
658
    GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
659
    GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
660
    GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
661
    GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
662
    GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
663
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
664
    }
665

    
666
///////////////////////////////////////////////////////////////////////////////////////////////////
667
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
668

    
669
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
670
    {
671
    mOITRenderProgram.useProgram();
672

    
673
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
674
    GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
675
    GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
676
    GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
677
    GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
678
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
679
    }
680

    
681
///////////////////////////////////////////////////////////////////////////////////////////////////
682

    
683
  static void setSSBOSize(float size)
684
    {
685
    mBufferSize = size;
686
    }
687

    
688
///////////////////////////////////////////////////////////////////////////////////////////////////
689
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
690
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
691

    
692
  private static void detectBuggyDrivers()
693
    {
694
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
695
    String version = GLES30.glGetString(GLES30.GL_VERSION);
696
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
697

    
698
    /*
699
    android.util.Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
700
    android.util.Log.e("DISTORTED", "GL Version "  +GLES30.glGetString(GLES31.GL_VERSION));
701
    android.util.Log.e("DISTORTED", "GL Vendor "   +GLES30.glGetString(GLES31.GL_VENDOR));
702
    android.util.Log.e("DISTORTED", "GL Renderer " +GLES30.glGetString(GLES31.GL_RENDERER));
703
    */
704

    
705
    if( vendor.contains("ARM") )
706
      {
707
      if( version.contains("r12") )
708
        {
709
        Log.e("DISTORTED", "You are running this on a ARM Mali driver r12.\nThis is a buggy driver, please update to r22. Problems with flashing expected.");
710
        }
711
      }
712
    else if( vendor.contains("Imagination") )
713
      {
714
      if( renderer.contains("GE8") )
715
        {
716
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
717
        }
718
      }
719
    }
720

    
721
///////////////////////////////////////////////////////////////////////////////////////////////////
722
/**
723
 * Return OpenGL ES version supported by the hardware we are running on.
724
 * There are only two possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
725
 */
726
  static int getGLSL()
727
    {
728
    return mGLSL;
729
    }
730

    
731
///////////////////////////////////////////////////////////////////////////////////////////////////
732
/**
733
 * Have we successfully managed to compile the OIT programs?
734
 * Some hardware ( Imagination GE8100 / 8300, driver build 1.8@4490469 present in my HTC phone and,
735
 * sadly, Amazon Fire Stick 4K ) fails to compile the shaders. See relevant thread in Imagination's
736
 * support forum:
737
 *
738
 * https://forums.imgtec.com/t/ge8100-in-htc-desire-12-android-7-1-1-fragment-shader-fails-to-compile/2708
739
 */
740
  public static boolean OITCompilationSuccessful()
741
    {
742
    return mOITCompilationSuccessful;
743
    }
744

    
745
///////////////////////////////////////////////////////////////////////////////////////////////////
746
/**
747
 * Have we called onCreate yet, ie have we initialized the library?
748
 * @return <code>true</code> if the library is initialized and ready for action.
749
 */
750
  public static boolean isInitialized()
751
    {
752
    return mInitialized;
753
    }
754

    
755
///////////////////////////////////////////////////////////////////////////////////////////////////
756
/**
757
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
758
 * I.e. best called from GLSurfaceView.onCreate().
759
 * <p>
760
 * Needs to be called from a thread holding the OpenGL context.
761
 *   
762
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
763
 */
764
  public static void onCreate(final Context context) throws Exception
765
    {
766
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
767
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
768

    
769
    int glESversion = configurationInfo.reqGlEsVersion;
770
    int major = glESversion >> 16;
771
    int minor = glESversion & 0xff;
772

    
773
    if( major< 3 )
774
      {
775
      mGLSL = 100*major + 10*minor;
776
      throw new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
777
      }
778
    else
779
      {
780
      mGLSL = (major==3 && minor==0) ? 300 : 310;
781
      }
782

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

    
786
    mInitialized = true;
787
    mOITCompilationSuccessful = false;
788

    
789
    detectBuggyDrivers();
790

    
791
    EffectMessageSender.startSending();
792

    
793
    final Resources resources = context.getResources();
794

    
795
    Exception exception=null;
796

    
797
    try
798
      {
799
      createPrograms(resources);
800
      }
801
    catch(Exception ex)
802
      {
803
      exception = ex;
804
      }
805

    
806
    if( mGLSL>=310)
807
      {
808
      try
809
        {
810
        createProgramsOIT(resources);
811
        mOITCompilationSuccessful = true;
812
        }
813
      catch(Exception ex)
814
        {
815
        exception = ex;
816
        }
817
      }
818

    
819
    try
820
      {
821
      EffectQueuePostprocess.createPrograms(resources, mGLSL);
822
      }
823
    catch(Exception ex)
824
      {
825
      exception = ex;
826
      }
827

    
828
    try
829
      {
830
      PostprocessEffect.createPrograms(mGLSL);
831
      }
832
    catch(Exception ex)
833
      {
834
      exception = ex;
835
      }
836

    
837
    if( exception!=null)
838
      {
839
      throw exception;
840
      }
841
    }
842

    
843
///////////////////////////////////////////////////////////////////////////////////////////////////
844
/**
845
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
846
 * Must be called from Activity.onPause().
847
 */
848
  public static void onPause()
849
    {
850
    InternalObject.onPause();
851

    
852
    mLinkedListSSBO[0]= -1;
853

    
854
    for(int i = 0; i< DistortedLibrary.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
855
    }
856

    
857
///////////////////////////////////////////////////////////////////////////////////////////////////
858
/**
859
 * Call this so that the Library can release its internal data structures.
860
 * Must be called from Activity.onDestroy(). 
861
 */
862
  public static void onDestroy()
863
    {
864
    InternalObject.onDestroy();
865
    InternalNodeData.onDestroy();
866
    InternalMaster.onDestroy();
867
    InternalOutputSurface.onDestroy();
868
    DistortedEffects.onDestroy();
869
    EffectQueue.onDestroy();
870
    Effect.onDestroy();
871
    EffectMessageSender.stopSending();
872

    
873
    mInitialized = false;
874
    }
875

    
876
///////////////////////////////////////////////////////////////////////////////////////////////////
877
/**
878
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
879
 * single (InputSurface,MeshBase) combo.
880
 *
881
 * @param type {@link EffectType}
882
 * @return The maximum number of effects of a given type.
883
 */
884
  @SuppressWarnings("unused")
885
  public static int getMax(EffectType type)
886
    {
887
    return EffectQueue.getMax(type.ordinal());
888
    }
889

    
890
///////////////////////////////////////////////////////////////////////////////////////////////////
891
/**
892
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
893
 * This can fail if:
894
 * <ul>
895
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
896
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
897
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onCreate}. After this
898
 *     time only decreasing the value of 'max' is permitted.
899
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
900
 * </ul>
901
 *
902
 * @param type {@link EffectType}
903
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
904
 *            than Byte.MAX_VALUE
905
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
906
 */
907
  @SuppressWarnings("unused")
908
  public static boolean setMax(EffectType type, int max)
909
    {
910
    return EffectQueue.setMax(type.ordinal(),max);
911
    }
912
  }
(3-3/14)