Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 06ddd60d

1 d333eb6b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4 46b572b5 Leszek Koltunski
// This file is part of Distorted.                                                               //
5 d333eb6b Leszek Koltunski
//                                                                                               //
6 46b572b5 Leszek Koltunski
// Distorted is free software: you can redistribute it and/or modify                             //
7 d333eb6b Leszek Koltunski
// 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 46b572b5 Leszek Koltunski
// Distorted is distributed in the hope that it will be useful,                                  //
12 d333eb6b Leszek Koltunski
// 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 46b572b5 Leszek Koltunski
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18 d333eb6b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
19
20 fe82a979 Leszek Koltunski
package org.distorted.library.main;
21 6a06a912 Leszek Koltunski
22 30beb34f Leszek Koltunski
import android.app.ActivityManager;
23 7845dc66 Leszek Koltunski
import android.content.Context;
24 30beb34f Leszek Koltunski
import android.content.pm.ConfigurationInfo;
25 d6e94c84 Leszek Koltunski
import android.content.res.Resources;
26 b7074bc6 Leszek Koltunski
import android.opengl.GLES30;
27 edea9cf3 Leszek Koltunski
import android.opengl.GLES31;
28 bfe45b4a Leszek Koltunski
import android.util.Log;
29 310e14fb leszek
30 bfe45b4a Leszek Koltunski
import org.distorted.library.R;
31 26a4e5f6 leszek
import org.distorted.library.effect.Effect;
32 809dcae3 Leszek Koltunski
import org.distorted.library.effectqueue.EffectQueue;
33
import org.distorted.library.effectqueue.EffectQueuePostprocess;
34 bfe45b4a Leszek Koltunski
import org.distorted.library.effect.EffectType;
35
import org.distorted.library.effect.FragmentEffect;
36 aa2f0486 Leszek Koltunski
import org.distorted.library.effect.PostprocessEffect;
37 bfe45b4a Leszek Koltunski
import org.distorted.library.effect.VertexEffect;
38 07206c71 Leszek Koltunski
import org.distorted.library.effectqueue.EffectQueueVertex;
39
import org.distorted.library.mesh.DeferredJobs;
40 bfe45b4a Leszek Koltunski
import org.distorted.library.mesh.MeshBase;
41 ed06301f Leszek Koltunski
import org.distorted.library.message.EffectMessageSender;
42 bfe45b4a Leszek Koltunski
import org.distorted.library.program.DistortedProgram;
43 b7074bc6 Leszek Koltunski
import org.distorted.library.program.VertexCompilationException;
44 bfe45b4a Leszek Koltunski
45
import java.io.InputStream;
46
import java.nio.ByteBuffer;
47
import java.nio.ByteOrder;
48
import java.nio.FloatBuffer;
49
import java.nio.IntBuffer;
50 5f35f1cb Leszek Koltunski
import java.util.regex.Matcher;
51
import java.util.regex.Pattern;
52 6a06a912 Leszek Koltunski
53
///////////////////////////////////////////////////////////////////////////////////////////////////
54
/**
55 f953bee0 Leszek Koltunski
 * A singleton class used to control various global dialog_settings.
56 6a06a912 Leszek Koltunski
 */
57 7602a827 Leszek Koltunski
public class DistortedLibrary
58 39cbf9dc Leszek Koltunski
  {
59 b7074bc6 Leszek Koltunski
  private static int mGLSL;
60
  private static String mGLSL_VERSION;
61 d99fcc9c Leszek Koltunski
  private static boolean mOITCompilationAttempted;
62 6a06a912 Leszek Koltunski
  /**
63 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedTexture from another instance, clone the Bitmap that's
64
   * backing up our DistortedTexture.
65 6a06a912 Leszek Koltunski
   * <p>
66 cacc63de Leszek Koltunski
   * This way we can have two DistortedTextures, both backed up by the same Bitmap, to which we can
67 6a06a912 Leszek Koltunski
   * apply different effects. Used in the copy constructor.
68
   */
69 29a06526 Leszek Koltunski
  public static final int CLONE_SURFACE = 0x1;
70 6a06a912 Leszek Koltunski
  /**
71 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedEffects from another instance, clone the Matrix Effects.
72 6a06a912 Leszek Koltunski
   * <p>
73 cacc63de Leszek Koltunski
   * This way we can have two different DistortedEffects sharing the MATRIX queue.
74 6a06a912 Leszek Koltunski
   */
75 015642fb Leszek Koltunski
  public static final int CLONE_MATRIX = 0x2;
76 6a06a912 Leszek Koltunski
  /**
77 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedEffects from another instance, clone the Vertex Effects.
78 6a06a912 Leszek Koltunski
   * <p>
79 cacc63de Leszek Koltunski
   * This way we can have two different DistortedEffects sharing the VERTEX queue.
80 6a06a912 Leszek Koltunski
   */
81
  public static final int CLONE_VERTEX  = 0x4;
82
  /**
83 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedEffects from another instance, clone the Fragment Effects.
84 6a06a912 Leszek Koltunski
   * <p>
85 cacc63de Leszek Koltunski
   * This way we can have two different DistortedEffects sharing the FRAGMENT queue.
86 6a06a912 Leszek Koltunski
   */
87
  public static final int CLONE_FRAGMENT= 0x8;
88 d6e94c84 Leszek Koltunski
   /**
89
   * When creating an instance of a DistortedEffects from another instance, clone the PostProcess Effects.
90
   * <p>
91
   * This way we can have two different DistortedEffects sharing the POSTPROCESS queue.
92
   */
93
  public static final int CLONE_POSTPROCESS= 0x10;
94 6a06a912 Leszek Koltunski
  /**
95 a09ada4c Leszek Koltunski
   * When creating an instance of a DistortedNode from another instance, clone the children Nodes.
96 6a06a912 Leszek Koltunski
   * <p>
97 cacc63de Leszek Koltunski
   * This is mainly useful for creating many similar sub-trees and rendering then at different places
98
   * on the screen with (optionally) different Effects.
99 6a06a912 Leszek Koltunski
   */
100 d6e94c84 Leszek Koltunski
  public static final int CLONE_CHILDREN= 0x20;
101 b3618cb5 Leszek Koltunski
102 5f35f1cb Leszek Koltunski
  /**
103
   * When creating a DistortedScreen (which needs to have mFBOQueueSize FBOs attached), pass this
104
   * constant for 'numOfFBOs' and the number of backing FBOs will be taken from 'mFBOQueueSize'
105
   * (the value of which is most likely unknown at the time of creation of the Screen)
106
   */
107
  public static final int WAIT_FOR_FBO_QUEUE_SIZE = -1;
108 586b5fa1 Leszek Koltunski
  /**
109
   * Work around bugs in ARM Mali driver by, instead to a single FBO, rendering to a circular queue
110 5f35f1cb Leszek Koltunski
   * of mFBOQueueSize FBOs. (otherwise we sometimes get a 'full pipeline flush' and the end result
111 586b5fa1 Leszek Koltunski
   * might be missing part of the Objects)
112 6672d895 Leszek Koltunski
   *
113 5f35f1cb Leszek Koltunski
   * This bug only exists on Mali driver r12. (or more precisely it's there in r12 but fixed in r22)
114 6672d895 Leszek Koltunski
   *
115
   * https://community.arm.com/graphics/f/discussions/10285/opengl-es-3-1-on-mali-t880-flashes
116 586b5fa1 Leszek Koltunski
   */
117 5f35f1cb Leszek Koltunski
  private static int mFBOQueueSize;
118 586b5fa1 Leszek Koltunski
119 55c14a19 Leszek Koltunski
  private static boolean mInitialized=false;
120 6a06a912 Leszek Koltunski
121 bfe45b4a Leszek Koltunski
  //////////////////////////////////////////////////////////////////////////////////////////////
122
  /// MAIN PROGRAM ///
123
  private static DistortedProgram mMainProgram;
124
  private static int mMainTextureH;
125
126
  /// NORMAL PROGRAM /////
127
  private static DistortedProgram mNormalProgram;
128
  private static int mNormalMVPMatrixH;
129
130
  /// MAIN OIT PROGRAM ///
131
  private static DistortedProgram mMainOITProgram;
132
  private static int mMainOITTextureH;
133
  private static int mMainOITSizeH;
134
  private static int mMainOITNumRecordsH;
135
136
  /// BLIT PROGRAM ///
137
  private static DistortedProgram mBlitProgram;
138
  private static int mBlitTextureH;
139
  private static int mBlitDepthH;
140
  private static final FloatBuffer mQuadPositions;
141
142 f046b159 Leszek Koltunski
  /// FULL PROGRAM ///
143
  private static DistortedProgram mFullProgram;
144
145 bfe45b4a Leszek Koltunski
  static
146
    {
147
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
148
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
149
    mQuadPositions.put(positionData).position(0);
150
    }
151
152
  /// BLIT DEPTH PROGRAM ///
153
  private static DistortedProgram mBlitDepthProgram;
154
  private static int mBlitDepthTextureH;
155
  private static int mBlitDepthDepthTextureH;
156
  private static int mBlitDepthDepthH;
157
  private static int mBlitDepthTexCorrH;
158
159
  /// OIT SSBO BUFFER ///
160
  private static int[] mLinkedListSSBO = new int[1];
161 5f35f1cb Leszek Koltunski
  private static int[] mAtomicCounter;
162 bfe45b4a Leszek Koltunski
  private static int   mCurrBuffer;
163
164
  static
165
    {
166
    mLinkedListSSBO[0]= -1;
167
    mCurrBuffer       =  0;
168
    }
169
170
  ///////////////////////////////////////////////////////////////
171
  // meaning: allocate 1.0 screenful of places for transparent
172
  // fragments in the SSBO backing up the OIT render method.
173
  private static float mBufferSize=1.0f;
174
175
  /// OIT CLEAR PROGRAM ///
176
  private static DistortedProgram mOITClearProgram;
177
  private static int mOITClearDepthH;
178
  private static int mOITClearTexCorrH;
179
  private static int mOITClearSizeH;
180
181
  /// OIT BUILD PROGRAM ///
182
  private static DistortedProgram mOITBuildProgram;
183
  private static int mOITBuildTextureH;
184
  private static int mOITBuildDepthTextureH;
185
  private static int mOITBuildDepthH;
186
  private static int mOITBuildTexCorrH;
187
  private static int mOITBuildSizeH;
188
  private static int mOITBuildNumRecordsH;
189
190
  /// OIT COLLAPSE PROGRAM ///
191
  private static DistortedProgram mOITCollapseProgram;
192
  private static int mOITCollapseDepthTextureH;
193
  private static int mOITCollapseDepthH;
194
  private static int mOITCollapseTexCorrH;
195
  private static int mOITCollapseSizeH;
196
197
  /// OIT RENDER PROGRAM ///
198
  private static DistortedProgram mOITRenderProgram;
199
  private static int mOITRenderDepthH;
200
  private static int mOITRenderTexCorrH;
201
  private static int mOITRenderSizeH;
202
203
  /// END PROGRAMS //////
204
205 d99fcc9c Leszek Koltunski
  /**
206
   * Every application using the library must implement this interface so that the library can send
207
   * it exceptions that arise. The exceptions may come at any time, for example the library will
208
   * compile its OIT problem only on the first attempt to use the OIT
209
   * Those will mainly be hardware-related: shaders do not compile on particular hardware, the required
210
   * OpenGL ES 3.0 is not supported, etc.
211
   */
212
  public interface ExceptionListener
213
    {
214
    void distortedException(Exception ex);
215
    }
216
217
  private static ExceptionListener mListener;
218
  private static Resources mResources;
219
220 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
221 c638c1b0 Leszek Koltunski
// private: hide this from Javadoc
222 6a06a912 Leszek Koltunski
223 7602a827 Leszek Koltunski
  private DistortedLibrary()
224 6a06a912 Leszek Koltunski
    {
225 8eccf334 Leszek Koltunski
226 6a06a912 Leszek Koltunski
    }
227
228 bfe45b4a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
229
230 d99fcc9c Leszek Koltunski
  private static void createMainProgram()
231 bfe45b4a Leszek Koltunski
    {
232
    // MAIN PROGRAM ////////////////////////////////////
233 d99fcc9c Leszek Koltunski
    final InputStream mainVertStream = mResources.openRawResource(R.raw.main_vertex_shader);
234
    final InputStream mainFragStream = mResources.openRawResource(R.raw.main_fragment_shader);
235 bfe45b4a Leszek Koltunski
236
    int numF = FragmentEffect.getNumEnabled();
237
    int numV = VertexEffect.getNumEnabled();
238
239 b7074bc6 Leszek Koltunski
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
240
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
241 36d65d88 Leszek Koltunski
242 e8925fcd Leszek Koltunski
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
243 36d65d88 Leszek Koltunski
244 bfe45b4a Leszek Koltunski
    String enabledEffectV= VertexEffect.getGLSL();
245
    String enabledEffectF= FragmentEffect.getGLSL();
246
247
    String[] feedback = { "v_Position", "v_endPosition" };
248
249
    try
250
      {
251
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
252 b7074bc6 Leszek Koltunski
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
253 bfe45b4a Leszek Koltunski
      }
254
    catch(Exception e)
255
      {
256
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
257
      throw new RuntimeException(e.getMessage());
258
      }
259
260
    int mainProgramH = mMainProgram.getProgramHandle();
261
    EffectQueue.getUniforms(mainProgramH,0);
262 36d65d88 Leszek Koltunski
    MeshBase.getUniforms(mainProgramH,0);
263 b7074bc6 Leszek Koltunski
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
264 bfe45b4a Leszek Koltunski
265
    // BLIT PROGRAM ////////////////////////////////////
266 d99fcc9c Leszek Koltunski
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
267
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
268 bfe45b4a Leszek Koltunski
269
    try
270
      {
271 b7074bc6 Leszek Koltunski
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
272 bfe45b4a Leszek Koltunski
      }
273
    catch(Exception e)
274
      {
275
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
276
      throw new RuntimeException(e.getMessage());
277
      }
278
279
    int blitProgramH = mBlitProgram.getProgramHandle();
280 b7074bc6 Leszek Koltunski
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
281
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
282 bfe45b4a Leszek Koltunski
283
    // BLIT DEPTH PROGRAM ////////////////////////////////////
284 d99fcc9c Leszek Koltunski
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
285
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
286 bfe45b4a Leszek Koltunski
287
    try
288
      {
289 b7074bc6 Leszek Koltunski
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
290 bfe45b4a Leszek Koltunski
      }
291
    catch(Exception e)
292
      {
293
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
294
      throw new RuntimeException(e.getMessage());
295
      }
296
297
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
298 b7074bc6 Leszek Koltunski
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
299
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
300
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
301
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
302 d99fcc9c Leszek Koltunski
    }
303
304
///////////////////////////////////////////////////////////////////////////////////////////////////
305 bfe45b4a Leszek Koltunski
306 d99fcc9c Leszek Koltunski
  private static void createNormalProgram(Resources resources)
307
    {
308 bfe45b4a Leszek Koltunski
    // NORMAL PROGRAM //////////////////////////////////////
309
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
310
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
311
312
    try
313
      {
314 b7074bc6 Leszek Koltunski
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
315 bfe45b4a Leszek Koltunski
      }
316
    catch(Exception e)
317
      {
318
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
319
      throw new RuntimeException(e.getMessage());
320
      }
321
322
    int normalProgramH = mNormalProgram.getProgramHandle();
323 b7074bc6 Leszek Koltunski
    mNormalMVPMatrixH  = GLES30.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
324 bfe45b4a Leszek Koltunski
    }
325
326 f046b159 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
327
328
  private static void createFullProgram(Resources resources)
329
    {
330
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
331
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
332
333
    int numV = VertexEffect.getAllEnabled();
334
335
    String fullVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX ) : 0 ) + "\n");
336
    String fullFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " +                                         0   + "\n");
337 36d65d88 Leszek Koltunski
338 e8925fcd Leszek Koltunski
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
339 36d65d88 Leszek Koltunski
340 f046b159 Leszek Koltunski
    String enabledEffectV= VertexEffect.getAllGLSL();
341
    String enabledEffectF= "{}";
342
343 667884b0 Leszek Koltunski
    fullVertHeader += "#define PREAPPLY\n";
344
345 e54bfada Leszek Koltunski
    String[] feedback = { "v_Position", "v_endPosition", "v_Inflate" };
346 f046b159 Leszek Koltunski
347
    try
348
      {
349
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
350
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
351
      }
352
    catch(Exception e)
353
      {
354
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
355
      throw new RuntimeException(e.getMessage());
356
      }
357
358
    int fullProgramH = mFullProgram.getProgramHandle();
359
    EffectQueue.getUniforms(fullProgramH,3);
360 36d65d88 Leszek Koltunski
    MeshBase.getUniforms(fullProgramH,3);
361 f046b159 Leszek Koltunski
    }
362
363 bfe45b4a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
364
365 d99fcc9c Leszek Koltunski
  private static void createOITProgram(Resources resources)
366 bfe45b4a Leszek Koltunski
    {
367
    // MAIN OIT PROGRAM ////////////////////////////////
368
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
369
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
370
371
    int numF = FragmentEffect.getNumEnabled();
372
    int numV = VertexEffect.getNumEnabled();
373
374 b7074bc6 Leszek Koltunski
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") + ("#define OIT\n");
375
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") + ("#define OIT\n");
376 bfe45b4a Leszek Koltunski
377 e8925fcd Leszek Koltunski
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
378 36d65d88 Leszek Koltunski
379 bfe45b4a Leszek Koltunski
    String enabledEffectV= VertexEffect.getGLSL();
380
    String enabledEffectF= FragmentEffect.getGLSL();
381
382
    try
383
      {
384
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
385 b7074bc6 Leszek Koltunski
                                             enabledEffectV, enabledEffectF, mGLSL, null);
386 bfe45b4a Leszek Koltunski
      }
387
    catch(Exception e)
388
      {
389
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
390
      throw new RuntimeException(e.getMessage());
391
      }
392
393
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
394
    EffectQueue.getUniforms(mainOITProgramH,1);
395 36d65d88 Leszek Koltunski
    MeshBase.getUniforms(mainOITProgramH,1);
396 b7074bc6 Leszek Koltunski
    mMainOITTextureH    = GLES30.glGetUniformLocation( mainOITProgramH, "u_Texture");
397
    mMainOITSizeH       = GLES30.glGetUniformLocation( mainOITProgramH, "u_Size");
398
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mainOITProgramH, "u_numRecords");
399 bfe45b4a Leszek Koltunski
400
    // OIT CLEAR PROGRAM ////////////////////////////////////
401
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
402
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
403
404
    try
405
      {
406 b7074bc6 Leszek Koltunski
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
407 bfe45b4a Leszek Koltunski
      }
408
    catch(Exception e)
409
      {
410
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
411
      throw new RuntimeException(e.getMessage());
412
      }
413
414
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
415 b7074bc6 Leszek Koltunski
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
416
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
417
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
418 bfe45b4a Leszek Koltunski
419
    // OIT BUILD PROGRAM ////////////////////////////////////
420
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
421
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
422
423
    try
424
      {
425 b7074bc6 Leszek Koltunski
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
426 bfe45b4a Leszek Koltunski
      }
427
    catch(Exception e)
428
      {
429
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
430
      throw new RuntimeException(e.getMessage());
431
      }
432
433
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
434 b7074bc6 Leszek Koltunski
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
435
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
436
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
437
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
438
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
439
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
440 bfe45b4a Leszek Koltunski
441
    // OIT COLLAPSE PROGRAM ///////////////////////////
442
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
443
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
444
445
    try
446
      {
447 b7074bc6 Leszek Koltunski
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
448 bfe45b4a Leszek Koltunski
      }
449
    catch(Exception e)
450
      {
451
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
452
      throw new RuntimeException(e.getMessage());
453
      }
454
455
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
456 b7074bc6 Leszek Koltunski
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
457
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
458
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
459
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
460 bfe45b4a Leszek Koltunski
461
    // OIT RENDER PROGRAM ///////////////////////////
462
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
463
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
464
465
    try
466
      {
467 b7074bc6 Leszek Koltunski
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
468 bfe45b4a Leszek Koltunski
      }
469
    catch(Exception e)
470
      {
471
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
472
      throw new RuntimeException(e.getMessage());
473
      }
474
475
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
476 b7074bc6 Leszek Koltunski
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
477
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
478
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
479 bfe45b4a Leszek Koltunski
    }
480
481
///////////////////////////////////////////////////////////////////////////////////////////////////
482
483
  private static void displayNormals(EffectQueue[] queues, MeshBase mesh)
484
    {
485 d99fcc9c Leszek Koltunski
    if( mNormalProgram==null )
486
      {
487
      try
488
        {
489
        createNormalProgram(mResources);
490
        }
491
      catch(Exception ex)
492
        {
493
        mListener.distortedException(ex);
494
        return;
495
        }
496
      }
497
498 bfe45b4a Leszek Koltunski
    int num = mesh.getNumVertices();
499
    int tfo = mesh.getTFO();
500
501 b7074bc6 Leszek Koltunski
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
502
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
503 7602a827 Leszek Koltunski
    InternalRenderState.switchOffDrawing();
504 b7074bc6 Leszek Koltunski
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
505 7602a827 Leszek Koltunski
    InternalRenderState.restoreDrawing();
506 b7074bc6 Leszek Koltunski
    GLES30.glEndTransformFeedback();
507
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
508 bfe45b4a Leszek Koltunski
509 f046b159 Leszek Koltunski
    mNormalProgram.useProgram();
510
    GLES30.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, EffectQueue.getMVP(queues) , 0);
511
    mesh.bindTransformAttribs(mNormalProgram);
512 b7074bc6 Leszek Koltunski
    GLES30.glLineWidth(8.0f);
513
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
514 bfe45b4a Leszek Koltunski
    }
515
516 f046b159 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
517
// execute all VertexEffects and adjust all vertices
518
519 07206c71 Leszek Koltunski
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
520 f046b159 Leszek Koltunski
    {
521 d99fcc9c Leszek Koltunski
    if( mFullProgram==null )
522 f046b159 Leszek Koltunski
      {
523 d99fcc9c Leszek Koltunski
      try
524
        {
525
        createFullProgram(mResources);
526
        }
527
      catch(Exception ex)
528
        {
529
        mListener.distortedException(ex);
530
        return;
531
        }
532 f046b159 Leszek Koltunski
      }
533 d99fcc9c Leszek Koltunski
534
    int num = mesh.getNumVertices();
535
    int tfo = mesh.getTFO();
536
537
    mFullProgram.useProgram();
538
    mesh.bindVertexAttribs(mFullProgram);
539
    queue.compute(1);
540
    queue.send(0.0f,3);
541
    mesh.send(3);
542
543
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
544
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
545
    InternalRenderState.switchOffDrawing();
546
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
547
    InternalRenderState.restoreDrawing();
548
    GLES30.glEndTransformFeedback();
549
    mesh.copyTransformToVertex();
550
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
551 f046b159 Leszek Koltunski
    }
552
553 bfe45b4a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
554
555 c90aca24 Leszek Koltunski
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
556 bfe45b4a Leszek Koltunski
    {
557 06ddd60d Leszek Koltunski
    if( mMainOITProgram!=null )
558
      {
559
      EffectQueue[] queues = effects.getQueues();
560 c90aca24 Leszek Koltunski
561 06ddd60d Leszek Koltunski
      EffectQueue.compute(queues, currTime);
562
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
563 bfe45b4a Leszek Koltunski
564 06ddd60d Leszek Koltunski
      mMainOITProgram.useProgram();
565
      GLES30.glUniform1i(mMainOITTextureH, 0);
566
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
567
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
568
      mesh.bindVertexAttribs(mMainOITProgram);
569
      mesh.send(1);
570 bfe45b4a Leszek Koltunski
571 06ddd60d Leszek Koltunski
      float inflate     = mesh.getInflate();
572
      float distance    = surface.mDistance;
573
      float mipmap      = surface.mMipmap;
574
      float[] projection= surface.mProjectionMatrix;
575 bfe45b4a Leszek Koltunski
576 06ddd60d Leszek Koltunski
      EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 1 );
577
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
578 bfe45b4a Leszek Koltunski
579 06ddd60d Leszek Koltunski
      if( mesh.getShowNormals() )
580
        {
581
        mMainProgram.useProgram();
582
        mesh.send(0);
583
        EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
584
        displayNormals(queues,mesh);
585
        }
586 bfe45b4a Leszek Koltunski
      }
587
    }
588
589
///////////////////////////////////////////////////////////////////////////////////////////////////
590
591 c90aca24 Leszek Koltunski
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
592 bfe45b4a Leszek Koltunski
    {
593 f046b159 Leszek Koltunski
    if( mMainProgram!=null )
594 f482efa3 Leszek Koltunski
      {
595
      EffectQueue[] queues = effects.getQueues();
596 bfe45b4a Leszek Koltunski
597 f482efa3 Leszek Koltunski
      EffectQueue.compute(queues, currTime);
598
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
599 46b572b5 Leszek Koltunski
600 f482efa3 Leszek Koltunski
      mMainProgram.useProgram();
601
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
602
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
603 36d65d88 Leszek Koltunski
      mesh.send(0);
604 809dcae3 Leszek Koltunski
605 f482efa3 Leszek Koltunski
      float inflate     = mesh.getInflate();
606
      float distance    = surface.mDistance;
607
      float mipmap      = surface.mMipmap;
608
      float[] projection= surface.mProjectionMatrix;
609 809dcae3 Leszek Koltunski
610 f482efa3 Leszek Koltunski
      EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
611
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
612 bfe45b4a Leszek Koltunski
613 f482efa3 Leszek Koltunski
      if( mesh.getShowNormals() ) displayNormals(queues,mesh);
614
      }
615 bfe45b4a Leszek Koltunski
    }
616
617
///////////////////////////////////////////////////////////////////////////////////////////////////
618
619 7602a827 Leszek Koltunski
  static void blitPriv(InternalOutputSurface surface)
620 bfe45b4a Leszek Koltunski
    {
621 f482efa3 Leszek Koltunski
    if( mBlitProgram!=null )
622
      {
623
      mBlitProgram.useProgram();
624 bfe45b4a Leszek Koltunski
625 f482efa3 Leszek Koltunski
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
626
      GLES30.glUniform1i(mBlitTextureH, 0);
627
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
628
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
629
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
630
      }
631 bfe45b4a Leszek Koltunski
    }
632
633
///////////////////////////////////////////////////////////////////////////////////////////////////
634
635 7602a827 Leszek Koltunski
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
636 bfe45b4a Leszek Koltunski
    {
637 f482efa3 Leszek Koltunski
    if( mBlitDepthProgram!=null )
638
      {
639
      mBlitDepthProgram.useProgram();
640
641
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
642
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
643
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
644
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
645
      GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
646
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
647
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
648
      }
649 bfe45b4a Leszek Koltunski
    }
650
651
///////////////////////////////////////////////////////////////////////////////////////////////////
652 b7074bc6 Leszek Koltunski
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
653 bfe45b4a Leszek Koltunski
654
  private static int printPreviousBuffer()
655
    {
656
    int counter = 0;
657
658 b7074bc6 Leszek Koltunski
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
659
                                                                GLES30.GL_MAP_READ_BIT);
660 bfe45b4a Leszek Koltunski
    if( atomicBuf!=null )
661
      {
662
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
663
      counter = atomicIntBuf.get(0);
664
      }
665
    else
666
      {
667 b7074bc6 Leszek Koltunski
      Log.e("effects", "print: failed to map atomic buffer");
668 bfe45b4a Leszek Koltunski
      }
669
670 b7074bc6 Leszek Koltunski
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
671 bfe45b4a Leszek Koltunski
672
    return counter;
673
    }
674
675
///////////////////////////////////////////////////////////////////////////////////////////////////
676
677
  private static void zeroBuffer()
678
    {
679 b7074bc6 Leszek Koltunski
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
680
        GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
681 bfe45b4a Leszek Koltunski
    if( atomicBuf!=null )
682
      {
683
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
684
      atomicIntBuf.put(0,0);
685
      }
686
    else
687
      {
688 b7074bc6 Leszek Koltunski
      Log.e("effects", "zero: failed to map atomic buffer");
689 bfe45b4a Leszek Koltunski
      }
690
691 b7074bc6 Leszek Koltunski
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
692 bfe45b4a Leszek Koltunski
    }
693
694
///////////////////////////////////////////////////////////////////////////////////////////////////
695
// reset atomic counter to 0
696
697
  static int zeroOutAtomic()
698
    {
699
    int counter = 0;
700
701 5f35f1cb Leszek Koltunski
    if( mAtomicCounter==null )
702 bfe45b4a Leszek Koltunski
      {
703 5f35f1cb Leszek Koltunski
      mAtomicCounter = new int[mFBOQueueSize];
704
705
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
706 bfe45b4a Leszek Koltunski
707 5f35f1cb Leszek Koltunski
      for(int i=0; i<mFBOQueueSize; i++)
708 bfe45b4a Leszek Koltunski
        {
709 b7074bc6 Leszek Koltunski
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
710
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
711 bfe45b4a Leszek Koltunski
        zeroBuffer();
712
        }
713
      }
714
715
    // reading the value of the buffer on every frame would slow down rendering by
716 d99fcc9c Leszek Koltunski
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
717 bfe45b4a Leszek Koltunski
    if( mCurrBuffer==0 )
718
      {
719 b7074bc6 Leszek Koltunski
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
720 bfe45b4a Leszek Koltunski
      counter = printPreviousBuffer();
721
      }
722
723 5f35f1cb Leszek Koltunski
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
724 bfe45b4a Leszek Koltunski
725 b7074bc6 Leszek Koltunski
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
726 bfe45b4a Leszek Koltunski
    zeroBuffer();
727
728
    return counter;
729
    }
730
731
///////////////////////////////////////////////////////////////////////////////////////////////////
732 809dcae3 Leszek Koltunski
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
733 bfe45b4a Leszek Koltunski
734 7602a827 Leszek Koltunski
  static void oitClear(InternalOutputSurface surface, int counter)
735 bfe45b4a Leszek Koltunski
    {
736 d99fcc9c Leszek Koltunski
    if( mOITClearProgram==null )
737 bfe45b4a Leszek Koltunski
      {
738 d99fcc9c Leszek Koltunski
      if( mGLSL>=310 && !mOITCompilationAttempted )
739 f482efa3 Leszek Koltunski
        {
740 d99fcc9c Leszek Koltunski
        mOITCompilationAttempted = true;
741 bfe45b4a Leszek Koltunski
742 d99fcc9c Leszek Koltunski
        try
743
          {
744
          createOITProgram(mResources);
745
          }
746
        catch(Exception ex)
747
          {
748
          mListener.distortedException(ex);
749
          return;
750
          }
751 f482efa3 Leszek Koltunski
        }
752 d99fcc9c Leszek Koltunski
      else
753 f482efa3 Leszek Koltunski
        {
754 d99fcc9c Leszek Koltunski
        return;
755 f482efa3 Leszek Koltunski
        }
756 d99fcc9c Leszek Koltunski
      }
757 bfe45b4a Leszek Koltunski
758 d99fcc9c Leszek Koltunski
    if( mLinkedListSSBO[0]<0 )
759
      {
760
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
761 bfe45b4a Leszek Koltunski
762 d99fcc9c Leszek Koltunski
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
763
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
764
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
765
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
766
767
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
768
      }
769
770
    // See if we have overflown the SSBO in one of the previous frames.
771
    // If yes, assume we need to make the SSBO larger.
772
    float overflow = counter/(mBufferSize*surface.mWidth*surface.mHeight);
773
774
    if( overflow>1.0f )
775
      {
776
      mBufferSize *= (int)(overflow+1.0f);
777
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
778
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
779
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
780
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
781 f482efa3 Leszek Koltunski
      }
782 d99fcc9c Leszek Koltunski
783
    mOITClearProgram.useProgram();
784
785
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
786
    GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
787
    GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
788
    GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
789
    GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
790
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
791 bfe45b4a Leszek Koltunski
    }
792
793
///////////////////////////////////////////////////////////////////////////////////////////////////
794
// Pass2 of the OIT algorithm - build per-pixel linked lists.
795
796 7602a827 Leszek Koltunski
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
797 bfe45b4a Leszek Koltunski
    {
798 f482efa3 Leszek Koltunski
    if( mOITBuildProgram!=null )
799
      {
800
      mOITBuildProgram.useProgram();
801
802
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
803
      GLES30.glUniform1i(mOITBuildTextureH, 0);
804
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
805
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
806
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
807
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
808
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
809
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
810
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
811
      }
812 bfe45b4a Leszek Koltunski
    }
813
814
///////////////////////////////////////////////////////////////////////////////////////////////////
815
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
816
817 7602a827 Leszek Koltunski
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
818 bfe45b4a Leszek Koltunski
    {
819 f482efa3 Leszek Koltunski
    if( mOITCollapseProgram!=null )
820
      {
821
      mOITCollapseProgram.useProgram();
822
823
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
824
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
825
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
826
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
827
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
828
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
829
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
830
      }
831 bfe45b4a Leszek Koltunski
    }
832
833
///////////////////////////////////////////////////////////////////////////////////////////////////
834
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
835
836 7602a827 Leszek Koltunski
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
837 bfe45b4a Leszek Koltunski
    {
838 f482efa3 Leszek Koltunski
    if( mOITRenderProgram!=null )
839
      {
840
      mOITRenderProgram.useProgram();
841
842
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
843
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
844
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
845
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
846
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
847
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
848
      }
849 bfe45b4a Leszek Koltunski
    }
850
851
///////////////////////////////////////////////////////////////////////////////////////////////////
852
853
  static void setSSBOSize(float size)
854
    {
855
    mBufferSize = size;
856
    }
857
858 5f35f1cb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
859
860
  static int getQueueSize()
861
    {
862
    return mFBOQueueSize;
863
    }
864
865 edea9cf3 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
866
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
867 b7074bc6 Leszek Koltunski
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
868 edea9cf3 Leszek Koltunski
869 5f35f1cb Leszek Koltunski
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
870 edea9cf3 Leszek Koltunski
    {
871 b7074bc6 Leszek Koltunski
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
872
    String version = GLES30.glGetString(GLES30.GL_VERSION);
873
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
874 edea9cf3 Leszek Koltunski
875 5f35f1cb Leszek Koltunski
    mFBOQueueSize = 1;
876 edea9cf3 Leszek Koltunski
877
    if( vendor.contains("ARM") )
878
      {
879 5f35f1cb Leszek Koltunski
      try
880 edea9cf3 Leszek Koltunski
        {
881 5f35f1cb Leszek Koltunski
        String regex = ".*r(\\d+)p\\d.*";
882
        Pattern pattern = Pattern.compile(regex);
883
        Matcher matcher = pattern.matcher(version);
884
885
        if( matcher.find() )
886
          {
887
          String driverVersion = matcher.group(1);
888
889
          if( driverVersion!=null )
890
            {
891
            int drvVersion = Integer.parseInt(driverVersion);
892
893
            if( drvVersion<22 )
894
              {
895
              Log.e("DISTORTED", "You are running this on a ARM Mali driver r"+driverVersion+".\n" +
896
                    "This is a buggy driver, please update to r22. Inserting workaround which uses a lot of memory.");
897
898
              mFBOQueueSize = queueSize;
899
              }
900
            }
901
          }
902
        }
903
      catch(Exception ex)
904
        {
905
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
906 edea9cf3 Leszek Koltunski
        }
907
      }
908
    else if( vendor.contains("Imagination") )
909
      {
910
      if( renderer.contains("GE8") )
911
        {
912 b7074bc6 Leszek Koltunski
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
913 a79650a2 Leszek Koltunski
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
914 edea9cf3 Leszek Koltunski
        }
915
      }
916
    }
917
918 b7074bc6 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
919
/**
920
 * Return OpenGL ES version supported by the hardware we are running on.
921 60fdf71d Leszek Koltunski
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
922
 * or 200 (OpenGL ES 2.0)
923 b7074bc6 Leszek Koltunski
 */
924 60fdf71d Leszek Koltunski
  public static int getGLSL()
925 b7074bc6 Leszek Koltunski
    {
926
    return mGLSL;
927
    }
928
929 421c2728 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
930 310e14fb leszek
/**
931
 * Have we called onCreate yet, ie have we initialized the library?
932 1dfc9074 leszek
 * @return <code>true</code> if the library is initialized and ready for action.
933 310e14fb leszek
 */
934
  public static boolean isInitialized()
935 421c2728 Leszek Koltunski
    {
936 55c14a19 Leszek Koltunski
    return mInitialized;
937 421c2728 Leszek Koltunski
    }
938
939 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
940
/**
941 c43abe6c Leszek Koltunski
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
942 432442f9 Leszek Koltunski
 * I.e. best called from GLSurfaceView.onCreate().
943 6a06a912 Leszek Koltunski
 * <p>
944 432442f9 Leszek Koltunski
 * Needs to be called from a thread holding the OpenGL context.
945 5f35f1cb Leszek Koltunski
 *
946 015642fb Leszek Koltunski
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
947 d99fcc9c Leszek Koltunski
 * @param listener The library will send all (asynchronous!) exceptions there.
948 6a06a912 Leszek Koltunski
 */
949 d99fcc9c Leszek Koltunski
  public static void onCreate(final Context context, final ExceptionListener listener)
950 5f35f1cb Leszek Koltunski
    {
951 d99fcc9c Leszek Koltunski
    onCreate(context,listener,4);
952 5f35f1cb Leszek Koltunski
    }
953
954
///////////////////////////////////////////////////////////////////////////////////////////////////
955
/**
956
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
957
 * I.e. best called from GLSurfaceView.onCreate().
958
 * <p>
959
 * Needs to be called from a thread holding the OpenGL context.
960
 *   
961
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
962 d99fcc9c Leszek Koltunski
 * @param listener The library will send all (asynchronous!) exceptions there.
963 5f35f1cb Leszek Koltunski
 * @param queueSize the size of the FBO queue, a workaround for the bug on Mali drivers.
964
 */
965 d99fcc9c Leszek Koltunski
  public static void onCreate(final Context context, final ExceptionListener listener, int queueSize)
966 d6e94c84 Leszek Koltunski
    {
967 30beb34f Leszek Koltunski
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
968
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
969 b7074bc6 Leszek Koltunski
970
    int glESversion = configurationInfo.reqGlEsVersion;
971
    int major = glESversion >> 16;
972
    int minor = glESversion & 0xff;
973
974 d99fcc9c Leszek Koltunski
    mListener = listener;
975
976 b7074bc6 Leszek Koltunski
    if( major< 3 )
977
      {
978
      mGLSL = 100*major + 10*minor;
979 d99fcc9c Leszek Koltunski
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
980
      mListener.distortedException(ex);
981 b7074bc6 Leszek Koltunski
      }
982
    else
983
      {
984
      mGLSL = (major==3 && minor==0) ? 300 : 310;
985
      }
986
987
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+major+"."+minor);
988
    mGLSL_VERSION = "#version "+mGLSL+" es\n";
989 edea9cf3 Leszek Koltunski
990
    mInitialized = true;
991 d99fcc9c Leszek Koltunski
    mOITCompilationAttempted = false;
992 edea9cf3 Leszek Koltunski
993 5f35f1cb Leszek Koltunski
    detectBuggyDriversAndSetQueueSize(queueSize);
994 edea9cf3 Leszek Koltunski
995 0e924ba5 Leszek Koltunski
    EffectMessageSender.startSending();
996
997 d99fcc9c Leszek Koltunski
    mResources = context.getResources();
998 edea9cf3 Leszek Koltunski
999
    try
1000
      {
1001 d99fcc9c Leszek Koltunski
      createMainProgram();
1002 edea9cf3 Leszek Koltunski
      }
1003
    catch(Exception ex)
1004
      {
1005 d99fcc9c Leszek Koltunski
      mListener.distortedException(ex);
1006 edea9cf3 Leszek Koltunski
      }
1007
1008 f046b159 Leszek Koltunski
    try
1009
      {
1010 d99fcc9c Leszek Koltunski
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1011 f046b159 Leszek Koltunski
      }
1012
    catch(Exception ex)
1013
      {
1014 d99fcc9c Leszek Koltunski
      mListener.distortedException(ex);
1015 a13dde77 Leszek Koltunski
      }
1016
1017 edea9cf3 Leszek Koltunski
    try
1018
      {
1019 b7074bc6 Leszek Koltunski
      PostprocessEffect.createPrograms(mGLSL);
1020 edea9cf3 Leszek Koltunski
      }
1021
    catch(Exception ex)
1022
      {
1023 d99fcc9c Leszek Koltunski
      mListener.distortedException(ex);
1024 edea9cf3 Leszek Koltunski
      }
1025 6a06a912 Leszek Koltunski
    }
1026
1027 05ecc6fe Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
1028
/**
1029 78e89fb5 Leszek Koltunski
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1030 05ecc6fe Leszek Koltunski
 * Must be called from Activity.onPause().
1031
 */
1032
  public static void onPause()
1033
    {
1034 7602a827 Leszek Koltunski
    InternalObject.onPause();
1035 bfe45b4a Leszek Koltunski
1036
    mLinkedListSSBO[0]= -1;
1037 5f35f1cb Leszek Koltunski
    mAtomicCounter = null;
1038 05ecc6fe Leszek Koltunski
    }
1039
1040 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
1041
/**
1042
 * Call this so that the Library can release its internal data structures.
1043
 * Must be called from Activity.onDestroy(). 
1044
 */
1045
  public static void onDestroy()
1046
    {
1047 7602a827 Leszek Koltunski
    InternalObject.onDestroy();
1048
    InternalNodeData.onDestroy();
1049
    InternalMaster.onDestroy();
1050
    InternalOutputSurface.onDestroy();
1051 46b572b5 Leszek Koltunski
    DistortedEffects.onDestroy();
1052 42571056 Leszek Koltunski
    EffectQueue.onDestroy();
1053 26a4e5f6 leszek
    Effect.onDestroy();
1054 07206c71 Leszek Koltunski
    DeferredJobs.onDestroy();
1055 6a06a912 Leszek Koltunski
    EffectMessageSender.stopSending();
1056 f8686932 Leszek Koltunski
1057 55c14a19 Leszek Koltunski
    mInitialized = false;
1058 d99fcc9c Leszek Koltunski
    mOITCompilationAttempted = false;
1059
1060
    mNormalProgram     = null;
1061
    mMainOITProgram    = null;
1062
    mMainProgram       = null;
1063
    mFullProgram       = null;
1064
    mOITClearProgram   = null;
1065
    mOITBuildProgram   = null;
1066
    mOITCollapseProgram= null;
1067
    mOITRenderProgram  = null;
1068
    mBlitDepthProgram  = null;
1069
    mBlitProgram       = null;
1070 6a06a912 Leszek Koltunski
    }
1071 bfe45b4a Leszek Koltunski
1072
///////////////////////////////////////////////////////////////////////////////////////////////////
1073
/**
1074
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1075
 * single (InputSurface,MeshBase) combo.
1076
 *
1077
 * @param type {@link EffectType}
1078
 * @return The maximum number of effects of a given type.
1079
 */
1080
  @SuppressWarnings("unused")
1081
  public static int getMax(EffectType type)
1082
    {
1083
    return EffectQueue.getMax(type.ordinal());
1084
    }
1085
1086
///////////////////////////////////////////////////////////////////////////////////////////////////
1087
/**
1088
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1089
 * This can fail if:
1090
 * <ul>
1091
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1092
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1093 7602a827 Leszek Koltunski
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onCreate}. After this
1094 bfe45b4a Leszek Koltunski
 *     time only decreasing the value of 'max' is permitted.
1095
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1096
 * </ul>
1097
 *
1098
 * @param type {@link EffectType}
1099
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1100
 *            than Byte.MAX_VALUE
1101
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1102
 */
1103
  @SuppressWarnings("unused")
1104
  public static boolean setMax(EffectType type, int max)
1105
    {
1106
    return EffectQueue.setMax(type.ordinal(),max);
1107
    }
1108 f8f6d457 leszek
  }