Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 2faad666

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.opengl.GLES31;
23
import android.opengl.Matrix;
24

    
25
import org.distorted.library.effect.EffectQuality;
26

    
27
import java.nio.ByteBuffer;
28
import java.nio.ByteOrder;
29
import java.nio.IntBuffer;
30
import java.util.ArrayList;
31

    
32
///////////////////////////////////////////////////////////////////////////////////////////////////
33
/**
34
 * This is not really part of the public API.
35
 *
36
 * @y.exclude
37
 */
38
public abstract class DistortedOutputSurface extends DistortedSurface implements DistortedMaster.Slave
39
{
40
//////////// DEBUG FLAGS /////////////////////////////////////////////
41
/**
42
 * When rendering a Screen, show FPS in the upper-left corner?
43
 */
44
public static final int DEBUG_FPS = 1;
45
//////////// END DEBUG FLAGS /////////////////////////////////////////
46

    
47
/**
48
 * Do not create DEPTH or STENCIL attachment
49
 */
50
  public static final int NO_DEPTH_NO_STENCIL = 0;
51
/**
52
 * Create DEPTH, but not STENCIL
53
 */
54
  public static final int DEPTH_NO_STENCIL    = 1;
55
/**
56
 * Create both DEPTH and STENCIL
57
 */
58
  public static final int BOTH_DEPTH_STENCIL  = 2;
59

    
60
  private static final int ATTACH = 0;
61
  private static final int DETACH = 1;
62
  private static final int DETALL = 2;
63
  private static final int SORT   = 3;
64

    
65
  private ArrayList<DistortedNode> mChildren;
66
  private int mNumChildren;   // ==mChildren.length(), but we only create mChildren if the first one gets added
67

    
68
  private class Job
69
    {
70
    int type;
71
    DistortedNode node;
72

    
73
    Job(int t, DistortedNode n)
74
      {
75
      type = t;
76
      node = n;
77
      }
78
    }
79

    
80
  private ArrayList<Job> mJobs = new ArrayList<>();
81

    
82
  DistortedOutputSurface[] mBuffer;
83

    
84
  private long mTime;
85
  private float mFOV;
86
  float mDistance, mNear;
87
  float[] mProjectionMatrix;
88

    
89
  int mDepthStencilCreated;
90
  int mDepthStencil;
91
  int[] mDepthStencilH = new int[1];
92
  int[] mFBOH          = new int[1];
93

    
94
  private float mClearR, mClearG, mClearB, mClearA;
95
  private float mClearDepth;
96
  private int mClearStencil;
97
  private int mClear;
98
  float mMipmap;
99

    
100
  private int mDebugLevel;
101

    
102
  ////////////////////////////////////////////////////////////////////////////////
103
  // section dealing with Shader Storage Buffer Object (for counting transparency)
104
  private static final int FRAME_DELAY = 3;
105
  private static int mBufferSize       =10;
106
  private static DistortedObjectCounter mSurfaceCounter = new DistortedObjectCounter();
107
  private static int[] mSSBO = new int[1];
108
  private static IntBuffer mIntBuffer;
109

    
110
  static
111
    {
112
    mSSBO[0]= -1;
113
    }
114

    
115
  private int mSurfaceID;
116
  private int mLastIndex;
117
  private int[] mLastValue = new int[FRAME_DELAY];
118
  private int mLastDiff = -1;
119

    
120
  private static final int RUNNING_AVERAGE = 10;
121
  private int[] mRunningAvg = new int[RUNNING_AVERAGE];
122
  private int mAvgIndex;
123
  private int mAvgSum;
124
  // end section
125
  ////////////////////////////////////////////////////////////////////////////////
126

    
127
///////////////////////////////////////////////////////////////////////////////////////////////////
128

    
129
  abstract void prepareDebug(long time);
130
  abstract void renderDebug(long time);
131
  abstract void createSurface();
132
  abstract void deleteSurface();
133
  abstract void recreateSurface();
134

    
135
///////////////////////////////////////////////////////////////////////////////////////////////////
136

    
137
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
138
    {
139
    super(width,height,createColor,numcolors,type);
140

    
141
    mProjectionMatrix = new float[16];
142

    
143
    mFOV = 60.0f;
144
    mNear=  0.5f;
145

    
146
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
147
    mDepthStencil = depthStencil;
148

    
149
    mFBOH[0]         = fbo;
150
    mDepthStencilH[0]= 0;
151

    
152
    mTime = 0;
153
    mDebugLevel = 0;
154

    
155
    mClearR = 0.0f;
156
    mClearG = 0.0f;
157
    mClearB = 0.0f;
158
    mClearA = 0.0f;
159

    
160
    mClearDepth = 1.0f;
161
    mClearStencil = 0;
162
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
163

    
164
    mBuffer = new DistortedOutputSurface[1+EffectQuality.LENGTH];
165

    
166
    mMipmap = 1.0f;
167

    
168
    createProjection();
169
    }
170

    
171
///////////////////////////////////////////////////////////////////////////////////////////////////
172
// Must be called from a thread holding OpenGL Context
173

    
174
  void create()
175
    {
176
    if( mSSBO[0]<0 )
177
      {
178
      GLES31.glGenBuffers(1,mSSBO,0);
179

    
180
      // here bind the new SSBO and map it
181
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mSSBO[0]);
182
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, FRAME_DELAY *mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ);
183
      ByteBuffer buf = (ByteBuffer) GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, FRAME_DELAY *mBufferSize*4, GLES31.GL_MAP_READ_BIT );
184
      mIntBuffer = buf.order(ByteOrder.nativeOrder()).asIntBuffer();
185
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER,0, mSSBO[0]);
186
      }
187

    
188
    mSurfaceID = mSurfaceCounter.returnNext();
189

    
190
    if( mSurfaceID>=mBufferSize )
191
      {
192
      // increase size of the Buffer, copy over old values, remap.
193
      int[] tmp = new int[FRAME_DELAY *mBufferSize];
194
      for(int i = 0; i< FRAME_DELAY *mBufferSize; i++) tmp[i] = mIntBuffer.get(i);
195

    
196
      mBufferSize*= 2;
197

    
198
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0);
199
      GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER);
200
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER,0);
201

    
202
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mSSBO[0]);
203
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, FRAME_DELAY *mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ);
204
      ByteBuffer buf = (ByteBuffer) GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, FRAME_DELAY *mBufferSize*4, GLES31.GL_MAP_READ_BIT );
205
      mIntBuffer = buf.order(ByteOrder.nativeOrder()).asIntBuffer();
206
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER,0, mSSBO[0]);
207

    
208
      for(int i=0;i<tmp.length;i++) mIntBuffer.put(i,tmp[i]);
209
      }
210

    
211
    createSurface();
212
    }
213

    
214
///////////////////////////////////////////////////////////////////////////////////////////////////
215
// Must be called from a thread holding OpenGL Context
216

    
217
  void delete()
218
    {
219
    mSurfaceCounter.release(mSurfaceID);
220
    deleteSurface();
221
    }
222

    
223
///////////////////////////////////////////////////////////////////////////////////////////////////
224

    
225
  void recreate()
226
    {
227
    mSSBO[0]  = -1;
228
    mLastDiff = -1;
229

    
230
    for(int i = 0; i< FRAME_DELAY; i++) mLastValue[i] = 0;
231
    mSurfaceCounter.releaseAll();
232

    
233
    recreateSurface();
234
    }
235

    
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237

    
238
  int getNewCounter()
239
    {
240
    return FRAME_DELAY*mSurfaceID + mLastIndex;
241
    }
242

    
243
///////////////////////////////////////////////////////////////////////////////////////////////////
244

    
245
  private void createProjection()
246
    {
247
    if( mWidth>0 && mHeight>1 )
248
      {
249
      if( mFOV>0.0f )  // perspective projection
250
        {
251
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
252
        float q = mWidth*mNear;
253
        float c = mHeight*mNear;
254

    
255
        float left   = -q/2;
256
        float right  = +q/2;
257
        float bottom = -c/2;
258
        float top    = +c/2;
259
        float near   =  c/a;
260

    
261
        mDistance    = mHeight/a;
262
        float far    = 2*mDistance-near;
263

    
264
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
265
        }
266
      else             // parallel projection
267
        {
268
        float left   = -mWidth/2.0f;
269
        float right  = +mWidth/2.0f;
270
        float bottom = -mHeight/2.0f;
271
        float top    = +mHeight/2.0f;
272
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
273
        mDistance    = mWidth+mHeight;
274
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
275

    
276
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
277
        }
278
      }
279
    }
280

    
281
///////////////////////////////////////////////////////////////////////////////////////////////////
282

    
283
  private void createBuffers()
284
    {
285
    float mipmap=1.0f;
286

    
287
    for(int j=0; j<EffectQuality.LENGTH; j++)
288
      {
289
      mBuffer[j] = new DistortedFramebuffer(2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
290
      mBuffer[j].mMipmap = mipmap;
291
      mBuffer[j].mNear   = mNear;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
292
      mBuffer[j].glClearColor(1.0f,1.0f,1.0f,0.0f);
293
      mipmap *= EffectQuality.MULTIPLIER;
294
      }
295

    
296
    mBuffer[EffectQuality.LENGTH] = this;
297

    
298
    DistortedObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
299

    
300
    GLES31.glStencilMask(0xff);
301
    GLES31.glDepthMask(true);
302
    GLES31.glColorMask(true,true,true,true);
303
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
304
    GLES31.glClearDepthf(1.0f);
305
    GLES31.glClearStencil(0);
306

    
307
    for(int j=0; j<EffectQuality.LENGTH; j++)
308
      {
309
      mBuffer[j].setAsOutput();
310
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
311
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
312
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
313
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
314
      }
315
    }
316

    
317
///////////////////////////////////////////////////////////////////////////////////////////////////
318

    
319
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer)
320
    {
321
    GLES31.glViewport(0, 0, mWidth, mHeight);
322
    setAsOutput(currTime);
323
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
324
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[0]);
325
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
326
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
327

    
328
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
329
    GLES31.glStencilMask(0x00);
330

    
331
    DistortedEffects.blitDepthPriv(this);
332
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
333
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
334
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
335
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
336

    
337
    // clear buffers
338
    GLES31.glStencilMask(0xff);
339
    GLES31.glDepthMask(true);
340
    GLES31.glColorMask(true,true,true,true);
341
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
342
    GLES31.glClearDepthf(1.0f);
343
    GLES31.glClearStencil(0);
344

    
345
    buffer.setAsOutput();
346
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[1], 0);
347
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
348
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[0], 0);
349
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
350

    
351
    return 1;
352
    }
353

    
354
///////////////////////////////////////////////////////////////////////////////////////////////////
355
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
356
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
357
// to a whole buffer and merge it.
358

    
359
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
360
    {
361
    int quality=0, internalQuality = 0, numRenders = 0, bucketChange = 0;
362
    DistortedNode child1, child2;
363
    EffectQueuePostprocess lastQueue=null, currQueue;
364
    long lastBucket=0, currBucket;
365

    
366
    for(int i=0; i<numChildren; i++)
367
      {
368
      child1 = children.get(i);
369
      currQueue = child1.getPostprocessQueue();
370
      currBucket= currQueue.getID();
371

    
372
      if( currBucket==0 ) numRenders += child1.draw(time,this);
373
      else
374
        {
375
        if( mBuffer[0]==null ) createBuffers();
376

    
377
        if( lastBucket!=currBucket )
378
          {
379
          if( lastBucket!=0 )
380
            {
381
            for(int j=bucketChange; j<i; j++)
382
              {
383
              child2 = children.get(j);
384
              numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],lastQueue);
385
              }
386

    
387
            numRenders += lastQueue.postprocess(this);
388
            numRenders += blitWithDepth(time, mBuffer[quality]);
389
            }
390

    
391
          internalQuality = currQueue.getInternalQuality();
392
          quality         = currQueue.getQuality();
393
          bucketChange    = i;
394
          }
395

    
396
        child1.draw(time,mBuffer[quality]);
397
        //numRenders += currQueue.draw(child1,time,mBuffer);
398

    
399
        if( i==numChildren-1 )
400
          {
401
          for(int j=bucketChange; j<numChildren; j++)
402
            {
403
            child2 = children.get(j);
404
            numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],currQueue);
405
            }
406

    
407
          numRenders += currQueue.postprocess(this);
408
          numRenders += blitWithDepth(time, mBuffer[quality]);
409
          }
410
        }
411

    
412
      lastQueue = currQueue;
413
      lastBucket= currBucket;
414
      }
415

    
416
    return numRenders;
417
    }
418

    
419
///////////////////////////////////////////////////////////////////////////////////////////////////
420

    
421
  ArrayList<DistortedNode> getChildren()
422
    {
423
    return mChildren;
424
    }
425

    
426
///////////////////////////////////////////////////////////////////////////////////////////////////
427
// PUBLIC API
428
///////////////////////////////////////////////////////////////////////////////////////////////////
429
/**
430
 * Make the library show various debugging information.
431
 * <p>
432
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
433
 *
434
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
435
 */
436
  public void setDebug(int bitmask)
437
    {
438
    if( this instanceof DistortedScreen )
439
      mDebugLevel = bitmask;
440
    }
441

    
442
///////////////////////////////////////////////////////////////////////////////////////////////////
443

    
444
/**
445
 * Draws all the attached children to this OutputSurface.
446
 * <p>
447
 * Must be called from a thread holding OpenGL Context.
448
 *
449
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
450
 * @return Number of objects rendered.
451
 */
452
  public int render(long time)
453
    {
454
    if( mDebugLevel!=0 ) prepareDebug(time);
455

    
456
    // change tree topology (attach and detach children)
457
/*
458
    boolean changed1 =
459
*/
460
    DistortedMaster.toDo();
461
/*
462
    if( changed1 )
463
      {
464
      for(int i=0; i<mNumChildren; i++)
465
        {
466
        mChildren.get(i).debug(0);
467
        }
468

    
469
      DistortedNode.debugMap();
470
      }
471
*/
472
    // create and delete all underlying OpenGL resources
473
    // Watch out: FIRST change topology, only then deal
474
    // with OpenGL resources. That's because changing Tree
475
    // can result in additional Framebuffers that would need
476
    // to be created immediately, before the calls to drawRecursive()
477
/*
478
    boolean changed2 =
479
*/
480
    toDo();
481
/*
482
    if( changed2 )
483
      {
484
      DistortedObject.debugLists();
485
      }
486
*/
487
    // mark OpenGL state as unknown
488
    DistortedRenderState.reset();
489

    
490
    int numRenders=0;
491

    
492
    for(int i=0; i<mNumChildren; i++)
493
      {
494
      numRenders += mChildren.get(i).renderRecursive(time);
495
      }
496

    
497
    setAsOutput(time);
498
    numRenders += renderChildren(time,mNumChildren,mChildren);
499

    
500
    if( mDebugLevel != 0 ) renderDebug(time);
501

    
502
    return numRenders;
503
    }
504

    
505
///////////////////////////////////////////////////////////////////////////////////////////////////
506
/**
507
 * Bind this Surface as a Framebuffer we can render to.
508
 *
509
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
510
 *             out if this is the first time during present frame that this FBO is being set as output.
511
 *             If so, the library, in addition to binding the Surface for output, also clears the
512
 *             Surface's color and depth attachments.
513
 */
514
  public void setAsOutput(long time)
515
    {
516
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
517

    
518
    if( mTime!=time )
519
      {
520
      mTime = time;
521
      DistortedRenderState.colorDepthStencilOn();
522
      GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
523
      GLES31.glClearDepthf(mClearDepth);
524
      GLES31.glClearStencil(mClearStencil);
525
      GLES31.glClear(mClear);
526
      DistortedRenderState.colorDepthStencilRestore();
527

    
528
      if( mSSBO[0]>=0 )
529
        {
530
        // yes, this DOES keep on working when 'value' overflows into negative territory.
531
        int value = mIntBuffer.get(FRAME_DELAY*mSurfaceID+mLastIndex);
532

    
533
        if( value-mLastValue[mLastIndex]!=mLastDiff )
534
          {
535
          android.util.Log.d("surface", "id " + mSurfaceID +
536
              (mType == TYPE_USER ? " USER" : (mType == TYPE_SYST ? " SYST" : " TREE")) +
537
              " (" + mWidth + "x" + mHeight + ") last frame: " + (value - mLastValue[mLastIndex])
538
              + " avg: " + (mAvgSum/RUNNING_AVERAGE)
539
          );
540
          }
541

    
542
        mLastDiff = value-mLastValue[mLastIndex];
543
        mLastValue[mLastIndex] = value;
544

    
545
        mAvgSum += (mLastDiff-mRunningAvg[mAvgIndex]);
546
        mRunningAvg[mAvgIndex] = mLastDiff;
547
        if( ++mAvgIndex>=RUNNING_AVERAGE ) mAvgIndex =0;
548
        }
549

    
550
      if( ++mLastIndex >= FRAME_DELAY ) mLastIndex=0;
551
      }
552
    }
553

    
554
///////////////////////////////////////////////////////////////////////////////////////////////////
555
/**
556
 * Bind this Surface as a Framebuffer we can render to.
557
 * <p>
558
 * This version does not attempt to clear anything.
559
 */
560

    
561
  public void setAsOutput()
562
    {
563
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
564
    }
565

    
566
///////////////////////////////////////////////////////////////////////////////////////////////////
567
/**
568
 * Return the Near plane of the Projection included in the Surface.
569
 *
570
 * @return the Near plane.
571
 */
572
  public float getNear()
573
    {
574
    return mNear;
575
    }
576

    
577
///////////////////////////////////////////////////////////////////////////////////////////////////
578
/**
579
 * Set mipmap level.
580
 * <p>
581
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
582
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
583
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
584
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
585
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
586
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
587
 * <p>
588
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
589
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
590
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
591
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
592
 *
593
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
594
 *               does not make any sense (that would result in loss of speed and no gain in quality)
595
 */
596
  public void setMipmap(float mipmap)
597
    {
598
    mMipmap = mipmap;
599
    }
600

    
601
///////////////////////////////////////////////////////////////////////////////////////////////////
602
/**
603
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
604
 * this Surface at the beginning of each frame.
605
 *
606
 * @param r the Red component. Default: 0.0f
607
 * @param g the Green component. Default: 0.0f
608
 * @param b the Blue component. Default: 0.0f
609
 * @param a the Alpha component. Default: 0.0f
610
 */
611
  public void glClearColor(float r, float g, float b, float a)
612
    {
613
    mClearR = r;
614
    mClearG = g;
615
    mClearB = b;
616
    mClearA = a;
617
    }
618

    
619
///////////////////////////////////////////////////////////////////////////////////////////////////
620
/**
621
 * Uses glClearDepthf() to set up a value with which to clear
622
 * the Depth buffer of our Surface at the beginning of each frame.
623
 *
624
 * @param d the Depth. Default: 1.0f
625
 */
626
  public void glClearDepthf(float d)
627
    {
628
    mClearDepth = d;
629
    }
630

    
631
///////////////////////////////////////////////////////////////////////////////////////////////////
632
/**
633
 * Uses glClearStencil() to set up a value with which to clear the
634
 * Stencil buffer of our Surface at the beginning of each frame.
635
 *
636
 * @param s the Stencil. Default: 0
637
 */
638
  public void glClearStencil(int s)
639
    {
640
    mClearStencil = s;
641
    }
642

    
643
///////////////////////////////////////////////////////////////////////////////////////////////////
644
/**
645
 * Which buffers to Clear at the beginning of each frame?
646
 * <p>
647
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
648
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
649
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
650
 *
651
 * @param mask bitwise OR of BUFFER_BITs to clear.
652
 */
653
  public void glClear(int mask)
654
    {
655
    mClear = mask;
656
    }
657

    
658
///////////////////////////////////////////////////////////////////////////////////////////////////
659
/**
660
 * Create new Projection matrix.
661
 *
662
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
663
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
664
 * @param near Distance between the screen plane and the near plane.
665
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
666
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
667
 */
668
  public void setProjection(float fov, float near)
669
    {
670
    if( fov < 180.0f && fov >=0.0f )
671
      {
672
      mFOV = fov;
673
      }
674

    
675
    if( near<   1.0f && near> 0.0f )
676
      {
677
      mNear= near;
678
      }
679
    else if( near<=0.0f )
680
      {
681
      mNear = 0.01f;
682
      }
683
    else if( near>=1.0f )
684
      {
685
      mNear=0.99f;
686
      }
687

    
688
    if( mBuffer[0]!=null )
689
      {
690
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
691
      }
692

    
693
    createProjection();
694
    }
695

    
696
///////////////////////////////////////////////////////////////////////////////////////////////////
697
/**
698
 * Resize the underlying Framebuffer.
699
 * <p>
700
 * This method can be safely called mid-render as it doesn't interfere with rendering.
701
 *
702
 * @param width The new width.
703
 * @param height The new height.
704
 */
705
  public void resize(int width, int height)
706
    {
707
    if( mWidth!=width || mHeight!=height )
708
      {
709
      mWidth = width;
710
      mHeight= height;
711

    
712
      createProjection();
713

    
714
      if( mColorCreated==CREATED )
715
        {
716
        markForCreation();
717
        recreate();
718
        }
719
      }
720
    }
721

    
722
///////////////////////////////////////////////////////////////////////////////////////////////////
723
/**
724
 * Return true if the Surface contains a DEPTH attachment.
725
 *
726
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
727
 */
728
  public boolean hasDepth()
729
    {
730
    return mDepthStencilCreated==CREATED;
731
    }
732

    
733
///////////////////////////////////////////////////////////////////////////////////////////////////
734
/**
735
 * Return true if the Surface contains a STENCIL attachment.
736
 *
737
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
738
 */
739
  public boolean hasStencil()
740
    {
741
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
742
    }
743

    
744
///////////////////////////////////////////////////////////////////////////////////////////////////
745
/**
746
 * Adds a new child to the last position in the list of our Surface's children.
747
 * <p>
748
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
749
 * DistortedMaster (by calling doWork())
750
 *
751
 * @param node The new Node to add.
752
 */
753
  public void attach(DistortedNode node)
754
    {
755
    mJobs.add(new Job(ATTACH,node));
756
    DistortedMaster.newSlave(this);
757
    }
758

    
759
///////////////////////////////////////////////////////////////////////////////////////////////////
760
/**
761
 * Adds a new child to the last position in the list of our Surface's children.
762
 * <p>
763
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
764
 * DistortedMaster (by calling doWork())
765
 *
766
 * @param surface InputSurface to initialize our child Node with.
767
 * @param effects DistortedEffects to initialize our child Node with.
768
 * @param mesh MeshObject to initialize our child Node with.
769
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
770
 */
771
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
772
    {
773
    DistortedNode node = new DistortedNode(surface,effects,mesh);
774
    mJobs.add(new Job(ATTACH,node));
775
    DistortedMaster.newSlave(this);
776
    return node;
777
    }
778

    
779
///////////////////////////////////////////////////////////////////////////////////////////////////
780
/**
781
 * Removes the first occurrence of a specified child from the list of children of our Surface.
782
 * <p>
783
 * A bit questionable method as there can be many different Nodes attached as children, some
784
 * of them having the same Effects but - for instance - different Mesh. Use with care.
785
 * <p>
786
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
787
 * DistortedMaster (by calling doWork())
788
 *
789
 * @param effects DistortedEffects to remove.
790
 */
791
  public void detach(DistortedEffects effects)
792
    {
793
    long id = effects.getID();
794
    DistortedNode node;
795
    boolean detached = false;
796

    
797
    for(int i=0; i<mNumChildren; i++)
798
      {
799
      node = mChildren.get(i);
800

    
801
      if( node.getEffects().getID()==id )
802
        {
803
        detached = true;
804
        mJobs.add(new Job(DETACH,node));
805
        DistortedMaster.newSlave(this);
806
        break;
807
        }
808
      }
809

    
810
    if( !detached )
811
      {
812
      // if we failed to detach any, it still might be the case that
813
      // there's an ATTACH job that we need to cancel.
814
      int num = mJobs.size();
815
      Job job;
816

    
817
      for(int i=0; i<num; i++)
818
        {
819
        job = mJobs.get(i);
820

    
821
        if( job.type==ATTACH && job.node.getEffects()==effects )
822
          {
823
          mJobs.remove(i);
824
          break;
825
          }
826
        }
827
      }
828
    }
829

    
830
///////////////////////////////////////////////////////////////////////////////////////////////////
831
/**
832
 * Removes the first occurrence of a specified child from the list of children of our Surface.
833
 * <p>
834
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
835
 * DistortedMaster (by calling doWork())
836
 *
837
 * @param node The Node to remove.
838
 */
839
  public void detach(DistortedNode node)
840
    {
841
    mJobs.add(new Job(DETACH,node));
842
    DistortedMaster.newSlave(this);
843
    }
844

    
845
///////////////////////////////////////////////////////////////////////////////////////////////////
846
/**
847
 * Removes all children Nodes.
848
 * <p>
849
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
850
 * DistortedMaster (by calling doWork())
851
 */
852
  public void detachAll()
853
    {
854
    mJobs.add(new Job(DETALL,null));
855
    DistortedMaster.newSlave(this);
856
    }
857

    
858
///////////////////////////////////////////////////////////////////////////////////////////////////
859
/**
860
 * This is not really part of the public API. Has to be public only because it is a part of the
861
 * DistortedSlave interface, which should really be a class that we extend here instead but
862
 * Java has no multiple inheritance.
863
 *
864
 * @y.exclude
865
 */
866
  public void doWork()
867
    {
868
    int num = mJobs.size();
869
    Job job;
870

    
871
    for(int i=0; i<num; i++)
872
      {
873
      job = mJobs.remove(0);
874

    
875
      switch(job.type)
876
        {
877
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
878
                     job.node.setSurfaceParent(this);
879
                     DistortedMaster.addSorted(mChildren,job.node);
880
                     mNumChildren++;
881
                     break;
882
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
883
                       {
884
                       job.node.setSurfaceParent(null);
885
                       mNumChildren--;
886
                       }
887
                     break;
888
        case DETALL: if( mNumChildren>0 )
889
                       {
890
                       DistortedNode tmp;
891

    
892
                       for(int j=mNumChildren-1; j>=0; j--)
893
                         {
894
                         tmp = mChildren.remove(j);
895
                         tmp.setSurfaceParent(null);
896
                         }
897

    
898
                       mNumChildren = 0;
899
                       }
900
                     break;
901
        case SORT  : mChildren.remove(job.node);
902
                     DistortedMaster.addSorted(mChildren,job.node);
903
                     break;
904
        }
905
      }
906
    }
907
}
(9-9/22)