Project

General

Profile

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

library / src / main / java / org / distorted / library / Distorted.java @ a56bc359

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

    
22
import java.io.BufferedReader;
23
import java.io.IOException;
24
import java.io.InputStream;
25
import java.io.InputStreamReader;
26

    
27
import android.content.Context;
28
import android.opengl.GLES20;
29
import android.os.Build;
30
import android.util.Log;
31

    
32
import org.distorted.library.exception.*;
33

    
34
///////////////////////////////////////////////////////////////////////////////////////////////////
35
/**
36
 * A singleton class used to control various global settings.
37
 */
38
public class Distorted 
39
  {
40
  /**
41
   * When creating an instance of a DistortedObject from another instance, do not clone anything.
42
   * Used in the copy constructor.
43
   */
44
  public static final int CLONE_NOTHING = 0x0;
45
  /**
46
   * When creating an instance of a DistortedObject from another instance, clone the Bitmap that's
47
   * backing up our DistortedObject. 
48
   * <p>
49
   * This way we can have two DistortedObjects, both backed up by the same Bitmap, to which we can 
50
   * apply different effects. Used in the copy constructor.
51
   */
52
  public static final int CLONE_BITMAP  = 0x1;
53
  /**
54
   * When creating an instance of a DistortedObject from another instance, clone the Matrix Effects.
55
   * <p>
56
   * This way we can have two different DistortedObjects with different Bitmaps behind them, both 
57
   * always displayed in exactly the same place on the screen. Applying any matrix-based effect to 
58
   * one of them automatically applies the effect to the other. Used in the copy constructor.
59
   */
60
  public static final int CLONE_MATRIX = 0x2;
61
  /**
62
   * When creating an instance of a DistortedObject from another instance, clone the Vertex Effects.
63
   * <p>
64
   * This way we can have two different DistortedObjects with different Bitmaps behind them, both 
65
   * always with the same Vertex effects. Applying any vertex-based effect to one of them automatically 
66
   * applies the effect to the other. Used in the copy constructor.
67
   */
68
  public static final int CLONE_VERTEX  = 0x4;
69
  /**
70
   * When creating an instance of a DistortedObject from another instance, clone the Fragment Effects.
71
   * <p>
72
   * This way we can have two different DistortedObjects with different Bitmaps behind them, both 
73
   * always with the same Fragment effects. Applying any fragment-based effect to one of them automatically 
74
   * applies the effect to the other. Used in the copy constructor.
75
   */
76
  public static final int CLONE_FRAGMENT= 0x8;
77
  /**
78
   * When creating an instance of a DistortedNode from another instance, clone the children Nodes.
79
   * <p>
80
   * This is mainly useful for creating many similar sub-trees of Bitmaps and rendering then at different places
81
   * on the screen, with (optionally) different effects of the top-level root Bitmap.   
82
   */
83
  public static final int CLONE_CHILDREN= 0x10;
84

    
85
  private static final String TAG = Distorted.class.getSimpleName();
86
  private static boolean mInitialized = false;
87
  
88
  private static int mProgramH;         // handle to our shading program.
89
  private static int mTextureUniformH;  // the texture.
90

    
91
  static int mPositionH;                // model position information
92
  static int mNormalH;                  // model normal information.
93
  static int mTextureCoordH;            // model texture coordinate information.
94

    
95
  static DistortedFramebuffer mFramebuffer = new DistortedFramebuffer(0); // output to the screen
96

    
97
///////////////////////////////////////////////////////////////////////////////////////////////////
98

    
99
  private Distorted()
100
    {
101
    
102
    }
103

    
104
///////////////////////////////////////////////////////////////////////////////////////////////////
105
  
106
  private static void sanitizeMaxValues() throws VertexUniformsException,FragmentUniformsException
107
    {
108
    int maxV,maxF;  
109
    int[] param = new int[1];
110
    
111
    GLES20.glGetIntegerv(GLES20.GL_MAX_VERTEX_UNIFORM_VECTORS, param, 0);
112
    maxV = param[0];
113
    GLES20.glGetIntegerv(GLES20.GL_MAX_FRAGMENT_UNIFORM_VECTORS, param, 0);
114
    maxF = param[0];
115
    
116
    Log.d(TAG, "Max vectors in vertex shader: "+maxV);
117
    Log.d(TAG, "Max vectors in fragment shader: "+maxF);
118
    
119
    if( !Build.FINGERPRINT.contains("generic") )
120
      {
121
      int realMaxV = (maxV-11)/4;   // adjust this in case of changes to the shaders...
122
      int realMaxF = (maxF- 2)/4;   //
123
    
124
      if( getMaxVertex()   > realMaxV )
125
        {
126
        throw new VertexUniformsException("Too many effects in the vertex shader, max is "+realMaxV, realMaxV);
127
        }
128
      if( getMaxFragment() > realMaxF )
129
        {
130
        throw new FragmentUniformsException("Too many effects in the fragment shader, max is "+realMaxF, realMaxF);
131
        }
132
      }
133
    }
134
  
135
///////////////////////////////////////////////////////////////////////////////////////////////////
136

    
137
  private static int compileShader(final int shaderType, final String shaderSource) throws FragmentCompilationException,VertexCompilationException
138
    {
139
    int shaderHandle = GLES20.glCreateShader(shaderType);
140

    
141
    if (shaderHandle != 0) 
142
      {
143
      GLES20.glShaderSource(shaderHandle, "#version 100 \n"+ generateShaderHeader(shaderType) + shaderSource);
144
      GLES20.glCompileShader(shaderHandle);
145
      final int[] compileStatus = new int[1];
146
      GLES20.glGetShaderiv(shaderHandle, GLES20.GL_COMPILE_STATUS, compileStatus, 0);
147

    
148
      if (compileStatus[0] != GLES20.GL_TRUE ) 
149
        {
150
        GLES20.glDeleteShader(shaderHandle);
151
        shaderHandle = 0;
152
        }
153
      }
154

    
155
    if (shaderHandle == 0)
156
      {     
157
      String error = GLES20.glGetShaderInfoLog(shaderHandle);
158
     
159
      switch(shaderType)
160
        {
161
        case GLES20.GL_VERTEX_SHADER  : throw new VertexCompilationException(error); 
162
        case GLES20.GL_FRAGMENT_SHADER: throw new FragmentCompilationException(error);
163
        default                       : throw new RuntimeException(error);
164
        }
165
      }
166

    
167
    return shaderHandle;
168
    }
169

    
170
///////////////////////////////////////////////////////////////////////////////////////////////////
171

    
172
  private static int createAndLinkProgram(final int vertexShaderHandle, final int fragmentShaderHandle, final String[] attributes) throws LinkingException
173
    {
174
    int programHandle = GLES20.glCreateProgram();
175

    
176
    if (programHandle != 0) 
177
      {
178
      GLES20.glAttachShader(programHandle, vertexShaderHandle);         
179
      GLES20.glAttachShader(programHandle, fragmentShaderHandle);
180

    
181
      if (attributes != null)
182
        {
183
        final int size = attributes.length;
184

    
185
        for (int i = 0; i < size; i++)
186
          {
187
          GLES20.glBindAttribLocation(programHandle, i, attributes[i]);
188
          }                
189
        }
190

    
191
      GLES20.glLinkProgram(programHandle);
192

    
193
      final int[] linkStatus = new int[1];
194
      GLES20.glGetProgramiv(programHandle, GLES20.GL_LINK_STATUS, linkStatus, 0);
195

    
196
      if (linkStatus[0] != GLES20.GL_TRUE ) 
197
        {         
198
        String error = GLES20.glGetProgramInfoLog(programHandle);
199
        GLES20.glDeleteProgram(programHandle);
200
        throw new LinkingException(error);
201
        }
202
      
203
      final int[] numberOfUniforms = new int[1];
204
      GLES20.glGetProgramiv(programHandle, GLES20.GL_ACTIVE_UNIFORMS, numberOfUniforms, 0);
205

    
206
      android.util.Log.d(TAG, "number of active uniforms="+numberOfUniforms[0]);
207
      }
208
 
209
    return programHandle;
210
    }
211
 
212
///////////////////////////////////////////////////////////////////////////////////////////////////
213
  
214
  private static String generateShaderHeader(final int type)
215
    {
216
    String header="";
217
   
218
    switch(type)
219
      {
220
      case GLES20.GL_VERTEX_SHADER  : header += ("#define NUM_VERTEX "  + getMaxVertex()+"\n");
221
     
222
                                      for(EffectNames name: EffectNames.values() )
223
                                        {
224
                                        if( name.getType()==EffectTypes.VERTEX)
225
                                        header += ("#define "+name.name()+" "+name.ordinal()+"\n");  
226
                                        }
227
                                      break;
228
      case GLES20.GL_FRAGMENT_SHADER: header += ("#define NUM_FRAGMENT "+ getMaxFragment()+"\n");
229
     
230
                                      for(EffectNames name: EffectNames.values() )
231
                                        {
232
                                        if( name.getType()==EffectTypes.FRAGMENT)
233
                                        header += ("#define "+name.name()+" "+name.ordinal()+"\n");  
234
                                        }
235
                                      break;
236
     }
237
   
238
    //Log.d(TAG,""+header);
239
    
240
    return header;
241
    }
242
  
243
///////////////////////////////////////////////////////////////////////////////////////////////////
244
  
245
  private static String readTextFileFromRawResource(final Context c, final int resourceId)
246
    {
247
    final InputStream inputStream = c.getResources().openRawResource(resourceId);
248
    final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
249
    final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
250
 
251
    String nextLine;
252
    final StringBuilder body = new StringBuilder();
253
 
254
    try
255
      {
256
      while ((nextLine = bufferedReader.readLine()) != null)
257
        {
258
        body.append(nextLine);
259
        body.append('\n');
260
        }
261
      }
262
    catch (IOException e)
263
      {
264
      return null;
265
      }
266
 
267
    return body.toString();
268
    }
269
 
270
///////////////////////////////////////////////////////////////////////////////////////////////////
271
 
272
  private static String getVertexShader(final Context c)
273
    {
274
    return readTextFileFromRawResource( c, R.raw.main_vertex_shader);
275
    }
276
 
277
///////////////////////////////////////////////////////////////////////////////////////////////////
278
 
279
  private static String getFragmentShader(final Context c)
280
    {
281
    return readTextFileFromRawResource( c, R.raw.main_fragment_shader);
282
    }
283

    
284
///////////////////////////////////////////////////////////////////////////////////////////////////
285
// Public API
286
///////////////////////////////////////////////////////////////////////////////////////////////////
287
/**
288
 * Sets Vertical Field of View angle and the point the camera is looking at. This changes the Projection Matrix.
289
 *   
290
 * @param fov Vertical Field Of View angle, in degrees. If T is the middle of the top edge of the 
291
 *            screen, E is the eye point, and B is the middle of the bottom edge of the screen, then 
292
 *            fov = angle(TEB)
293
 * @param x   X-coordinate of the point the camera is looking at. -scrWidth/2 &lt; x &lt; scrWidth/2
294
 * @param y   Y-coordinate of the point the camera is looking at. -scrHeight/2 &lt; y &lt; scrHeight/2
295
 */
296
  public static void setProjection(float fov, float x, float y)
297
    {
298
    mFramebuffer.setProjection(fov,x,y);
299
    }
300
  
301
///////////////////////////////////////////////////////////////////////////////////////////////////
302
/**
303
 * When OpenGL context gets created, you need to call this method so that the library can initialise its internal data structures.
304
 * I.e. best called from GLSurfaceView.onSurfaceCreated().
305
 * <p>
306
 * Compiles the vertex and fragment shaders, establishes the addresses of all uniforms, and initialises all Bitmaps that have already
307
 * been created.
308
 *   
309
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
310
 * @throws FragmentCompilationException
311
 * @throws VertexCompilationException
312
 * @throws VertexUniformsException
313
 * @throws FragmentUniformsException
314
 * @throws LinkingException
315
 */
316
  public static void onSurfaceCreated(final Context context) throws FragmentCompilationException,VertexCompilationException,VertexUniformsException,FragmentUniformsException,LinkingException
317
    { 
318
    mInitialized = true;  
319

    
320
    final String vertexShader   = Distorted.getVertexShader(context);
321
    final String fragmentShader = Distorted.getFragmentShader(context);
322

    
323
    sanitizeMaxValues();
324
    
325
    final int vertexShaderHandle   = compileShader(GLES20.GL_VERTEX_SHADER  , vertexShader  );     
326
    final int fragmentShaderHandle = compileShader(GLES20.GL_FRAGMENT_SHADER, fragmentShader);     
327
      
328
    mProgramH = createAndLinkProgram(vertexShaderHandle, fragmentShaderHandle, new String[] {"a_Position",  "a_Color", "a_Normal", "a_TexCoordinate"});                                                            
329

    
330
    mFramebuffer.setProjection(60.0f,0.0f,0.0f);
331

    
332
    GLES20.glUseProgram(mProgramH);
333

    
334
    mTextureUniformH = GLES20.glGetUniformLocation(mProgramH, "u_Texture");
335
    mPositionH       = GLES20.glGetAttribLocation( mProgramH, "a_Position");
336
    mNormalH         = GLES20.glGetAttribLocation( mProgramH, "a_Normal");
337
    mTextureCoordH   = GLES20.glGetAttribLocation( mProgramH, "a_TexCoordinate");
338

    
339
    GLES20.glEnable (GLES20.GL_DEPTH_TEST);
340
    GLES20.glDepthFunc(GLES20.GL_LEQUAL);
341
    GLES20.glEnable(GLES20.GL_BLEND);
342
    GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
343
    GLES20.glEnable(GLES20.GL_CULL_FACE);
344
    GLES20.glCullFace(GLES20.GL_BACK);
345
    GLES20.glFrontFace(GLES20.GL_CW);
346
    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
347
    GLES20.glUniform1i(mTextureUniformH, 0);
348

    
349
    EffectQueueFragment.getUniforms(mProgramH);
350
    EffectQueueVertex.getUniforms(mProgramH);
351
    EffectQueueMatrix.getUniforms(mProgramH);
352
    
353
    GLES20.glEnableVertexAttribArray(mPositionH);        
354
    GLES20.glEnableVertexAttribArray(mNormalH);
355
    GLES20.glEnableVertexAttribArray(mTextureCoordH);
356
   
357
    DistortedObject.reset();
358
    DistortedNode.reset();
359
    EffectMessageSender.startSending();
360
    }
361
  
362
///////////////////////////////////////////////////////////////////////////////////////////////////
363
/**
364
 * Call this when the physical size of the surface we are rendering to changes.
365
 * I.e. must be called from GLSurfaceView.onSurfaceChanged()  
366
 *   
367
 * @param surfaceWidth  new width of the surface.
368
 * @param surfaceHeight new height of the surface.
369
 */
370
  public static void onSurfaceChanged(int surfaceWidth, int surfaceHeight)
371
    {
372
    mFramebuffer.resize(surfaceWidth,surfaceHeight);
373
    }
374

    
375
///////////////////////////////////////////////////////////////////////////////////////////////////
376
/**
377
 * Call this so that the Library can release its internal data structures.
378
 * Must be called from Activity.onDestroy(). 
379
 */
380
  public static void onDestroy()
381
    {
382
    DistortedObject.release();
383
    DistortedFramebuffer.release();
384
    DistortedNode.release();
385
    EffectQueue.release();
386
    EffectMessageSender.stopSending();
387
   
388
    mInitialized = false;
389
    }
390
  
391
///////////////////////////////////////////////////////////////////////////////////////////////////
392
/**
393
 * Returns the true if onSurfaceCreated has been called already, and thus if the Library's is ready
394
 * to accept effect requests.
395
 * 
396
 * @return <code>true</code> if the Library is ready for action, <code>false</code> otherwise.
397
 */
398
  public static boolean isInitialized()
399
    {
400
    return mInitialized;  
401
    }
402

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404
/**
405
 * Returns the maximum number of Matrix effects.
406
 *    
407
 * @return The maximum number of Matrix effects
408
 */
409
  public static int getMaxMatrix()
410
    {
411
    return EffectQueue.getMax(EffectTypes.MATRIX.ordinal());
412
    }
413
 
414
///////////////////////////////////////////////////////////////////////////////////////////////////
415
/**
416
 * Returns the maximum number of Vertex effects.
417
 *    
418
 * @return The maximum number of Vertex effects
419
 */  
420
  public static int getMaxVertex()
421
    {
422
    return EffectQueue.getMax(EffectTypes.VERTEX.ordinal());
423
    }
424
  
425
///////////////////////////////////////////////////////////////////////////////////////////////////
426
/**
427
 * Returns the maximum number of Fragment effects.
428
 *    
429
 * @return The maximum number of Fragment effects
430
 */  
431
  public static int getMaxFragment()
432
    {
433
    return EffectQueue.getMax(EffectTypes.FRAGMENT.ordinal());
434
    }
435

    
436
///////////////////////////////////////////////////////////////////////////////////////////////////
437
/**
438
 * Sets the maximum number of Matrix effects that can be applied to a single DistortedObject at one time.
439
 * This can fail if:
440
 * <ul>
441
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
442
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
443
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link #onSurfaceCreated}. After this
444
 *     time only decreasing the value of 'max' is permitted.
445
 * <li>Furthermore, this needs to be called before any DistortedObject gets created.
446
 * </ul>
447
 * 
448
 * @param max new maximum number of simultaneous Matrix Effects. Has to be a non-negative number not greater
449
 *            than Byte.MAX_VALUE 
450
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
451
 */
452
  public static boolean setMaxMatrix(int max)
453
    {
454
    return EffectQueue.setMax(EffectTypes.MATRIX.ordinal(),max);
455
    }
456
  
457
///////////////////////////////////////////////////////////////////////////////////////////////////
458
/**
459
 * Sets the maximum number of Vertex effects that can be applied to a single DistortedObject at one time.
460
 * This can fail if:
461
 * <ul>
462
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
463
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called 
464
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link #onSurfaceCreated}. After this
465
 *     time only decreasing the value of 'max' is permitted.
466
* <li>Furthermore, this needs to be called before any DistortedObject gets created.
467
 * </ul>
468
 * 
469
 * @param max new maximum number of simultaneous Vertex Effects. Has to be a non-negative number not greater
470
 *            than Byte.MAX_VALUE 
471
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
472
 */
473
  public static boolean setMaxVertex(int max)
474
    {
475
    return EffectQueue.setMax(EffectTypes.VERTEX.ordinal(),max);
476
    }
477

    
478
///////////////////////////////////////////////////////////////////////////////////////////////////
479
/**
480
 * Sets the maximum number of Fragment effects that can be applied to a single DistortedObject at one time.
481
 * This can fail if:
482
 * <ul>
483
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
484
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called 
485
 *     before the Fragment Shader gets compiled, i.e. before the call to {@link #onSurfaceCreated}. After this
486
 *     time only decreasing the value of 'max' is permitted.
487
 * <li>Furthermore, this needs to be called before any DistortedObject gets created.
488
 * </ul>
489
 * 
490
 * @param max new maximum number of simultaneous Fragment Effects. Has to be a non-negative number not greater
491
 *            than Byte.MAX_VALUE 
492
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
493
 */
494
  public static boolean setMaxFragment(int max)
495
    {
496
    return EffectQueue.setMax(EffectTypes.FRAGMENT.ordinal(),max);
497
    }
498
  }
(1-1/14)