Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 56c6ca24

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.util.ArrayList;
28

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

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

    
57
  private static final int ATTACH = 0;
58
  private static final int DETACH = 1;
59
  private static final int DETALL = 2;
60
  private static final int SORT   = 3;
61

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

    
65
  private class Job
66
    {
67
    int type;
68
    DistortedNode node;
69

    
70
    Job(int t, DistortedNode n)
71
      {
72
      type = t;
73
      node = n;
74
      }
75
    }
76

    
77
  private ArrayList<Job> mJobs = new ArrayList<>();
78

    
79
  // Global buffers used for postprocessing.
80
  private static DistortedOutputSurface[] mBuffer = new DistortedOutputSurface[EffectQuality.LENGTH];
81
  private static DistortedOutputSurface   mBufferOIT;
82

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

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

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

    
99
  private int mDebugLevel;
100

    
101
  int mRealWidth;   // the Surface can be backed up with a texture that is
102
  int mRealHeight;  // larger than the viewport we have to it.
103
                    // mWidth,mHeight are the sizes of the Viewport, those -
104
                    // sizes of the backing up texture.
105

    
106
///////////////////////////////////////////////////////////////////////////////////////////////////
107

    
108
  abstract void prepareDebug(long time);
109
  abstract void renderDebug(long time);
110

    
111
///////////////////////////////////////////////////////////////////////////////////////////////////
112

    
113
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
114
    {
115
    super(width,height,createColor,numcolors,type);
116

    
117
    mRealWidth = width;
118
    mRealHeight= height;
119

    
120
    mProjectionMatrix = new float[16];
121

    
122
    mFOV = 60.0f;
123
    mNear=  0.5f;
124

    
125
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
126
    mDepthStencil = depthStencil;
127

    
128
    mFBOH[0]         = fbo;
129
    mDepthStencilH[0]= 0;
130

    
131
    mTime = 0;
132
    mDebugLevel = 0;
133

    
134
    mClearR = 0.0f;
135
    mClearG = 0.0f;
136
    mClearB = 0.0f;
137
    mClearA = 0.0f;
138

    
139
    mClearDepth = 1.0f;
140
    mClearStencil = 0;
141
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
142

    
143
    mMipmap = 1.0f;
144

    
145
    createProjection();
146
    }
147

    
148
///////////////////////////////////////////////////////////////////////////////////////////////////
149

    
150
  private void createProjection()
151
    {
152
    if( mWidth>0 && mHeight>1 )
153
      {
154
      if( mFOV>0.0f )  // perspective projection
155
        {
156
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
157
        float q = mWidth*mNear;
158
        float c = mHeight*mNear;
159

    
160
        float left   = -q/2;
161
        float right  = +q/2;
162
        float bottom = -c/2;
163
        float top    = +c/2;
164
        float near   =  c/a;
165

    
166
        mDistance    = mHeight/a;
167
        float far    = 2*mDistance-near;
168

    
169
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
170
        }
171
      else             // parallel projection
172
        {
173
        float left   = -mWidth/2.0f;
174
        float right  = +mWidth/2.0f;
175
        float bottom = -mHeight/2.0f;
176
        float top    = +mHeight/2.0f;
177
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
178
        mDistance    = mWidth+mHeight;
179
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
180

    
181
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
182
        }
183
      }
184
    }
185

    
186
///////////////////////////////////////////////////////////////////////////////////////////////////
187

    
188
  private static void createPostprocessingBuffers(int width, int height, float near)
189
    {
190
    float mipmap=1.0f;
191

    
192
    for (int j=0; j<EffectQuality.LENGTH; j++)
193
      {
194
      mBuffer[j] = new DistortedFramebuffer(2, BOTH_DEPTH_STENCIL, TYPE_SYST, (int) (width * mipmap), (int) (height * mipmap));
195
      mBuffer[j].mMipmap = mipmap;
196
      mBuffer[j].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
197
      mBuffer[j].glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
198

    
199
      mipmap *= EffectQuality.MULTIPLIER;
200
      }
201

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

    
204
    GLES31.glStencilMask(0xff);
205
    GLES31.glDepthMask(true);
206
    GLES31.glColorMask(true, true, true, true);
207
    GLES31.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
208
    GLES31.glClearDepthf(1.0f);
209
    GLES31.glClearStencil(0);
210

    
211
    for (int j=0; j<EffectQuality.LENGTH; j++)
212
      {
213
      mBuffer[j].setAsOutput();
214
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
215
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_STENCIL_BUFFER_BIT);
216
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
217
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
218
      }
219
    }
220

    
221
///////////////////////////////////////////////////////////////////////////////////////////////////
222

    
223
  private static void initializeOIT(DistortedOutputSurface surface)
224
    {
225
    if( mBufferOIT==null )
226
      {
227
      mBufferOIT = new DistortedFramebuffer(1, BOTH_DEPTH_STENCIL, TYPE_SYST, surface.mWidth, surface.mHeight);
228
      mBufferOIT.mMipmap = 1.0f;
229
      mBufferOIT.mNear = surface.mNear;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
230
      mBufferOIT.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
231

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

    
234
      mBufferOIT.setAsOutput();
235
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBufferOIT.mColorH[0], 0);
236
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_STENCIL_BUFFER_BIT);
237
      }
238

    
239
    if( mBufferOIT.mWidth != surface.mWidth || mBufferOIT.mHeight != surface.mHeight )
240
      {
241
      mBufferOIT.mWidth  = (int)(surface.mWidth *mBufferOIT.mMipmap);
242
      mBufferOIT.mHeight = (int)(surface.mHeight*mBufferOIT.mMipmap);
243

    
244
      mBufferOIT.mNear   = surface.mNear;  // Near plane is independent of the mipmap level
245

    
246
      //android.util.Log.e("surface", "viewport "+i+" to ("+from.mWidth+"x"+from.mHeight+")");
247

    
248
      mBufferOIT.createProjection();
249

    
250
      int maxw = mBufferOIT.mWidth  > mBufferOIT.mRealWidth  ? mBufferOIT.mWidth  : mBufferOIT.mRealWidth;
251
      int maxh = mBufferOIT.mHeight > mBufferOIT.mRealHeight ? mBufferOIT.mHeight : mBufferOIT.mRealHeight;
252

    
253
      if (maxw > mBufferOIT.mRealWidth || maxh > mBufferOIT.mRealHeight)
254
        {
255
        mBufferOIT.mRealWidth = maxw;
256
        mBufferOIT.mRealHeight = maxh;
257

    
258
        mBufferOIT.recreate();
259
        mBufferOIT.create();
260
        }
261
      }
262

    
263
    if( mBufferOIT.mNear != surface.mNear || mBufferOIT.mFOV != surface.mFOV )
264
      {
265
      mBufferOIT.mNear = surface.mNear;
266
      mBufferOIT.mFOV  = surface.mFOV;
267
      mBufferOIT.createProjection();
268
      }
269

    
270
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBufferOIT.mFBOH[0]);
271

    
272
    DistortedRenderState.colorDepthStencilOn();
273
    GLES31.glClearColor(surface.mClearR, surface.mClearG, surface.mClearB, surface.mClearA);
274
    GLES31.glClearDepthf(surface.mClearDepth);
275
    GLES31.glClearStencil(surface.mClearStencil);
276
    GLES31.glClear(surface.mClear);
277
    DistortedRenderState.colorDepthStencilRestore();
278

    
279
    DistortedEffects.zeroOutAtomic();
280
    DistortedEffects.oitClear(surface);
281

    
282
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
283
    }
284

    
285
///////////////////////////////////////////////////////////////////////////////////////////////////
286

    
287
  static synchronized void onDestroy()
288
    {
289
    for(int j=0; j<EffectQuality.LENGTH; j++)
290
      {
291
      mBuffer[j] = null;
292
      }
293

    
294
    mBufferOIT = null;
295
    }
296

    
297
///////////////////////////////////////////////////////////////////////////////////////////////////
298
// The postprocessing buffers mBuffer[] are generally speaking too large (there's just one static
299
// set of them) so before we use them for output, we need to adjust the Vieport as if they were
300
// smaller. That takes care of outputting pixels to them. When we use them as input, we have to
301
// adjust the texture coords - see the get{Width|Height}Correction functions.
302

    
303
  private static void clonePostprocessingViewport(DistortedOutputSurface from)
304
    {
305
    if( mBuffer[0].mWidth != from.mWidth || mBuffer[0].mHeight != from.mHeight )
306
      {
307
      DistortedOutputSurface surface;
308

    
309
      for(int i=0; i<EffectQuality.LENGTH; i++)
310
        {
311
        surface = mBuffer[i];
312

    
313
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
314
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
315

    
316
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
317

    
318
        //android.util.Log.e("surface", "viewport "+i+" to ("+from.mWidth+"x"+from.mHeight+")");
319

    
320
        surface.createProjection();
321

    
322
        int maxw = surface.mWidth  > surface.mRealWidth  ? surface.mWidth  : surface.mRealWidth;
323
        int maxh = surface.mHeight > surface.mRealHeight ? surface.mHeight : surface.mRealHeight;
324

    
325
        if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
326
          {
327
          surface.mRealWidth = maxw;
328
          surface.mRealHeight = maxh;
329

    
330
          surface.recreate();
331
          surface.create();
332
          }
333
        }
334
      }
335
    }
336

    
337
///////////////////////////////////////////////////////////////////////////////////////////////////
338

    
339
  private int oitBuild(long currTime, DistortedOutputSurface buffer)
340
    {
341
    GLES31.glViewport(0, 0, mWidth, mHeight);
342
    setAsOutput(currTime);
343
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
344
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[0]);
345
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
346
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
347

    
348
    //GLES31.glDisable(GLES31.GL_STENCIL_TEST);
349
    //GLES31.glStencilMask(0x00);
350

    
351
    DistortedRenderState.colorDepthStencilOn();
352
    DistortedRenderState.enableDepthTest();
353

    
354
    DistortedEffects.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
355
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
356
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
357
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
358
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
359

    
360
    DistortedRenderState.colorDepthStencilRestore();
361
    DistortedRenderState.restoreDepthTest();
362

    
363
    return 1;
364
    }
365

    
366
///////////////////////////////////////////////////////////////////////////////////////////////////
367

    
368
  private int oitRender(long currTime, DistortedOutputSurface buffer)
369
    {
370
    GLES31.glViewport(0, 0, mWidth, mHeight);
371
    setAsOutput(currTime);
372
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
373
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[0]);
374
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
375
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
376

    
377
    DistortedRenderState.enableStencil();
378

    
379
    DistortedEffects.oitRender(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
380
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
381
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
382

    
383
    DistortedRenderState.restoreStencil();
384

    
385
    return 1;
386
    }
387

    
388
///////////////////////////////////////////////////////////////////////////////////////////////////
389

    
390
  private void clearBuffer(DistortedOutputSurface buffer)
391
    {
392
    GLES31.glStencilMask(0xff);
393
    GLES31.glDepthMask(true);
394
    GLES31.glColorMask(true,true,true,true);
395
    GLES31.glClearColor(1.0f,1.0f,1.0f,0.0f);
396
    GLES31.glClearDepthf(1.0f);
397
    GLES31.glClearStencil(0);
398

    
399
    buffer.setAsOutput();
400
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[1], 0);
401
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
402
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[0], 0);
403
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
404
    }
405

    
406
///////////////////////////////////////////////////////////////////////////////////////////////////
407
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
408
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
409
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild).
410

    
411
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
412
    {
413
    int quality=0, internalQuality = 0, numRenders = 0, bucketChange = 0;
414
    DistortedNode child1, child2;
415
    EffectQueuePostprocess lastQueue=null, currQueue;
416
    long lastBucket=0, currBucket=0;
417

    
418
    initializeOIT(this);
419

    
420
    for(int i=0; i<numChildren; i++)
421
      {
422
      child1 = children.get(i);
423
      currQueue = child1.getPostprocessQueue();
424
      currBucket= currQueue.getID();
425

    
426
      if( currBucket==0 )
427
        {
428
        GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBufferOIT.mFBOH[0]);
429
        numRenders += child1.draw(time, mBufferOIT);
430

    
431
        //setAsOutput(time);
432
        //numRenders += child1.draw(time,this);
433
        }
434
      else
435
        {
436
        if( mBuffer[0]==null ) createPostprocessingBuffers(mWidth,mHeight,mNear);
437

    
438
        if( lastBucket!=currBucket )
439
          {
440
          if( lastBucket==0 )
441
            {
442
            clonePostprocessingViewport(this);
443
            }
444
          else
445
            {
446
            for(int j=bucketChange; j<i; j++)
447
              {
448
              child2 = children.get(j);
449
              numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],lastQueue);
450
              }
451

    
452
            numRenders += lastQueue.postprocess(mBuffer);
453
            numRenders += mBufferOIT.oitBuild(time, mBuffer[quality]);
454
            clearBuffer(mBuffer[quality]);
455
            }
456

    
457
          internalQuality = currQueue.getInternalQuality();
458
          quality         = currQueue.getQuality();
459
          bucketChange    = i;
460
          }
461

    
462
        mBuffer[quality].setAsOutput(time);
463
        child1.drawNoBlend(time,mBuffer[quality]);
464

    
465
        if( i==numChildren-1 )
466
          {
467
          for(int j=bucketChange; j<numChildren; j++)
468
            {
469
            child2 = children.get(j);
470
            numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],currQueue);
471
            }
472

    
473
          numRenders += currQueue.postprocess(mBuffer);
474
          numRenders += mBufferOIT.oitBuild(time, mBuffer[quality]);
475
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT);
476
          numRenders += oitRender(time,mBufferOIT);  // merge the OIT linked list
477
          clearBuffer(mBuffer[quality]);
478
          }
479
        } // end else (postprocessed child)
480

    
481
      lastQueue = currQueue;
482
      lastBucket= currBucket;
483
      } // end main for loop
484

    
485
    if( currBucket==0 ) // there was no postprocessing - we need to merge the main buffer
486
      {
487
      numRenders += oitRender(time,mBufferOIT);
488
      }
489

    
490
    return numRenders;
491
    }
492

    
493
///////////////////////////////////////////////////////////////////////////////////////////////////
494

    
495
  ArrayList<DistortedNode> getChildren()
496
    {
497
    return mChildren;
498
    }
499

    
500
///////////////////////////////////////////////////////////////////////////////////////////////////
501
/**
502
 * Not part of the Public API.
503
 *
504
 * @y.exclude
505
 */
506
  public float getWidthCorrection()
507
    {
508
    return (float)mWidth/mRealWidth;
509
    }
510

    
511
///////////////////////////////////////////////////////////////////////////////////////////////////
512
/**
513
 * Not part of the Public API.
514
 *
515
 * @y.exclude
516
 */
517
  public float getHeightCorrection()
518
    {
519
    return (float)mHeight/mRealHeight;
520
    }
521

    
522
///////////////////////////////////////////////////////////////////////////////////////////////////
523
// PUBLIC API
524
///////////////////////////////////////////////////////////////////////////////////////////////////
525
/**
526
 * Make the library show various debugging information.
527
 * <p>
528
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
529
 *
530
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
531
 */
532
  public void setDebug(int bitmask)
533
    {
534
    if( this instanceof DistortedScreen )
535
      mDebugLevel = bitmask;
536
    }
537

    
538
///////////////////////////////////////////////////////////////////////////////////////////////////
539

    
540
/**
541
 * Draws all the attached children to this OutputSurface.
542
 * <p>
543
 * Must be called from a thread holding OpenGL Context.
544
 *
545
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
546
 * @return Number of objects rendered.
547
 */
548
  public int render(long time)
549
    {
550
    if( mDebugLevel!=0 ) prepareDebug(time);
551

    
552
    // change tree topology (attach and detach children)
553
/*
554
    boolean changed1 =
555
*/
556
    DistortedMaster.toDo();
557
/*
558
    if( changed1 )
559
      {
560
      for(int i=0; i<mNumChildren; i++)
561
        {
562
        mChildren.get(i).debug(0);
563
        }
564

    
565
      DistortedNode.debugMap();
566
      }
567
*/
568
    // create and delete all underlying OpenGL resources
569
    // Watch out: FIRST change topology, only then deal
570
    // with OpenGL resources. That's because changing Tree
571
    // can result in additional Framebuffers that would need
572
    // to be created immediately, before the calls to drawRecursive()
573
/*
574
    boolean changed2 =
575
*/
576
    toDo();
577
/*
578
    if( changed2 )
579
      {
580
      DistortedObject.debugLists();
581
      }
582
*/
583
    // mark OpenGL state as unknown
584
    DistortedRenderState.reset();
585

    
586
    int numRenders=0;
587

    
588
    for(int i=0; i<mNumChildren; i++)
589
      {
590
      numRenders += mChildren.get(i).renderRecursive(time);
591
      }
592

    
593
    setAsOutput(time);
594
    numRenders += renderChildren(time,mNumChildren,mChildren);
595

    
596
    if( mDebugLevel != 0 ) renderDebug(time);
597

    
598
    return numRenders;
599
    }
600

    
601
///////////////////////////////////////////////////////////////////////////////////////////////////
602
/**
603
 * Bind this Surface as a Framebuffer we can render to.
604
 *
605
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
606
 *             out if this is the first time during present frame that this FBO is being set as output.
607
 *             If so, the library, in addition to binding the Surface for output, also clears the
608
 *             Surface's color and depth attachments.
609
 */
610
  public void setAsOutput(long time)
611
    {
612
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
613

    
614
    if( mTime!=time )
615
      {
616
      mTime = time;
617
      DistortedRenderState.colorDepthStencilOn();
618
      GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
619
      GLES31.glClearDepthf(mClearDepth);
620
      GLES31.glClearStencil(mClearStencil);
621
      GLES31.glClear(mClear);
622
      DistortedRenderState.colorDepthStencilRestore();
623
      }
624
    }
625

    
626
///////////////////////////////////////////////////////////////////////////////////////////////////
627
/**
628
 * Bind this Surface as a Framebuffer we can render to.
629
 * <p>
630
 * This version does not attempt to clear anything.
631
 */
632

    
633
  public void setAsOutput()
634
    {
635
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
636
    }
637

    
638
///////////////////////////////////////////////////////////////////////////////////////////////////
639
/**
640
 * Return the Near plane of the Projection included in the Surface.
641
 *
642
 * @return the Near plane.
643
 */
644
  public float getNear()
645
    {
646
    return mNear;
647
    }
648

    
649
///////////////////////////////////////////////////////////////////////////////////////////////////
650
/**
651
 * Set mipmap level.
652
 * <p>
653
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
654
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
655
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
656
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
657
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
658
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
659
 * <p>
660
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
661
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
662
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
663
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
664
 *
665
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
666
 *               does not make any sense (that would result in loss of speed and no gain in quality)
667
 */
668
  public void setMipmap(float mipmap)
669
    {
670
    mMipmap = mipmap;
671
    }
672

    
673
///////////////////////////////////////////////////////////////////////////////////////////////////
674
/**
675
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
676
 * this Surface at the beginning of each frame.
677
 *
678
 * @param r the Red component. Default: 0.0f
679
 * @param g the Green component. Default: 0.0f
680
 * @param b the Blue component. Default: 0.0f
681
 * @param a the Alpha component. Default: 0.0f
682
 */
683
  public void glClearColor(float r, float g, float b, float a)
684
    {
685
    mClearR = r;
686
    mClearG = g;
687
    mClearB = b;
688
    mClearA = a;
689
    }
690

    
691
///////////////////////////////////////////////////////////////////////////////////////////////////
692
/**
693
 * Uses glClearDepthf() to set up a value with which to clear
694
 * the Depth buffer of our Surface at the beginning of each frame.
695
 *
696
 * @param d the Depth. Default: 1.0f
697
 */
698
  public void glClearDepthf(float d)
699
    {
700
    mClearDepth = d;
701
    }
702

    
703
///////////////////////////////////////////////////////////////////////////////////////////////////
704
/**
705
 * Uses glClearStencil() to set up a value with which to clear the
706
 * Stencil buffer of our Surface at the beginning of each frame.
707
 *
708
 * @param s the Stencil. Default: 0
709
 */
710
  public void glClearStencil(int s)
711
    {
712
    mClearStencil = s;
713
    }
714

    
715
///////////////////////////////////////////////////////////////////////////////////////////////////
716
/**
717
 * Which buffers to Clear at the beginning of each frame?
718
 * <p>
719
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
720
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
721
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
722
 *
723
 * @param mask bitwise OR of BUFFER_BITs to clear.
724
 */
725
  public void glClear(int mask)
726
    {
727
    mClear = mask;
728
    }
729

    
730
///////////////////////////////////////////////////////////////////////////////////////////////////
731
/**
732
 * Create new Projection matrix.
733
 *
734
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
735
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
736
 * @param near Distance between the screen plane and the near plane.
737
 *             Valid vaules: 0<near<1. When near==0 (illegal!), the Near Plane is exactly at the tip of
738
 *             the pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
739
 */
740
  public void setProjection(float fov, float near)
741
    {
742
    if( fov < 180.0f && fov >=0.0f )
743
      {
744
      mFOV = fov;
745
      }
746

    
747
    if( near<   1.0f && near> 0.0f )
748
      {
749
      mNear= near;
750
      }
751
    else if( near<=0.0f )
752
      {
753
      mNear = 0.01f;
754
      }
755
    else if( near>=1.0f )
756
      {
757
      mNear=0.99f;
758
      }
759

    
760
    createProjection();
761
    }
762

    
763
///////////////////////////////////////////////////////////////////////////////////////////////////
764
/**
765
 * Resize the underlying Framebuffer.
766
 * <p>
767
 * This method can be safely called mid-render as it doesn't interfere with rendering.
768
 *
769
 * @param width The new width.
770
 * @param height The new height.
771
 */
772
  public void resize(int width, int height)
773
    {
774
    if( mWidth!=width || mHeight!=height )
775
      {
776
      mWidth = mRealWidth = width;
777
      mHeight= mRealHeight= height;
778

    
779
      createProjection();
780

    
781
      if( mColorCreated==CREATED )
782
        {
783
        markForCreation();
784
        recreate();
785
        }
786
      }
787
    }
788

    
789
///////////////////////////////////////////////////////////////////////////////////////////////////
790
/**
791
 * Return true if the Surface contains a DEPTH attachment.
792
 *
793
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
794
 */
795
  public boolean hasDepth()
796
    {
797
    return mDepthStencilCreated==CREATED;
798
    }
799

    
800
///////////////////////////////////////////////////////////////////////////////////////////////////
801
/**
802
 * Return true if the Surface contains a STENCIL attachment.
803
 *
804
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
805
 */
806
  public boolean hasStencil()
807
    {
808
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
809
    }
810

    
811
///////////////////////////////////////////////////////////////////////////////////////////////////
812
/**
813
 * Adds a new child to the last position in the list of our Surface's children.
814
 * <p>
815
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
816
 * DistortedMaster (by calling doWork())
817
 *
818
 * @param node The new Node to add.
819
 */
820
  public void attach(DistortedNode node)
821
    {
822
    mJobs.add(new Job(ATTACH,node));
823
    DistortedMaster.newSlave(this);
824
    }
825

    
826
///////////////////////////////////////////////////////////////////////////////////////////////////
827
/**
828
 * Adds a new child to the last position in the list of our Surface's children.
829
 * <p>
830
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
831
 * DistortedMaster (by calling doWork())
832
 *
833
 * @param surface InputSurface to initialize our child Node with.
834
 * @param effects DistortedEffects to initialize our child Node with.
835
 * @param mesh MeshObject to initialize our child Node with.
836
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
837
 */
838
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
839
    {
840
    DistortedNode node = new DistortedNode(surface,effects,mesh);
841
    mJobs.add(new Job(ATTACH,node));
842
    DistortedMaster.newSlave(this);
843
    return node;
844
    }
845

    
846
///////////////////////////////////////////////////////////////////////////////////////////////////
847
/**
848
 * Removes the first occurrence of a specified child from the list of children of our Surface.
849
 * <p>
850
 * A bit questionable method as there can be many different Nodes attached as children, some
851
 * of them having the same Effects but - for instance - different Mesh. Use with care.
852
 * <p>
853
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
854
 * DistortedMaster (by calling doWork())
855
 *
856
 * @param effects DistortedEffects to remove.
857
 */
858
  public void detach(DistortedEffects effects)
859
    {
860
    long id = effects.getID();
861
    DistortedNode node;
862
    boolean detached = false;
863

    
864
    for(int i=0; i<mNumChildren; i++)
865
      {
866
      node = mChildren.get(i);
867

    
868
      if( node.getEffects().getID()==id )
869
        {
870
        detached = true;
871
        mJobs.add(new Job(DETACH,node));
872
        DistortedMaster.newSlave(this);
873
        break;
874
        }
875
      }
876

    
877
    if( !detached )
878
      {
879
      // if we failed to detach any, it still might be the case that
880
      // there's an ATTACH job that we need to cancel.
881
      int num = mJobs.size();
882
      Job job;
883

    
884
      for(int i=0; i<num; i++)
885
        {
886
        job = mJobs.get(i);
887

    
888
        if( job.type==ATTACH && job.node.getEffects()==effects )
889
          {
890
          mJobs.remove(i);
891
          break;
892
          }
893
        }
894
      }
895
    }
896

    
897
///////////////////////////////////////////////////////////////////////////////////////////////////
898
/**
899
 * Removes the first occurrence of a specified child from the list of children of our Surface.
900
 * <p>
901
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
902
 * DistortedMaster (by calling doWork())
903
 *
904
 * @param node The Node to remove.
905
 */
906
  public void detach(DistortedNode node)
907
    {
908
    mJobs.add(new Job(DETACH,node));
909
    DistortedMaster.newSlave(this);
910
    }
911

    
912
///////////////////////////////////////////////////////////////////////////////////////////////////
913
/**
914
 * Removes all children Nodes.
915
 * <p>
916
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
917
 * DistortedMaster (by calling doWork())
918
 */
919
  public void detachAll()
920
    {
921
    mJobs.add(new Job(DETALL,null));
922
    DistortedMaster.newSlave(this);
923
    }
924

    
925
///////////////////////////////////////////////////////////////////////////////////////////////////
926
/**
927
 * This is not really part of the public API. Has to be public only because it is a part of the
928
 * DistortedSlave interface, which should really be a class that we extend here instead but
929
 * Java has no multiple inheritance.
930
 *
931
 * @y.exclude
932
 */
933
  public void doWork()
934
    {
935
    int num = mJobs.size();
936
    Job job;
937

    
938
    for(int i=0; i<num; i++)
939
      {
940
      job = mJobs.remove(0);
941

    
942
      switch(job.type)
943
        {
944
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
945
                     job.node.setSurfaceParent(this);
946
                     DistortedMaster.addSorted(mChildren,job.node);
947
                     mNumChildren++;
948
                     break;
949
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
950
                       {
951
                       job.node.setSurfaceParent(null);
952
                       mNumChildren--;
953
                       }
954
                     break;
955
        case DETALL: if( mNumChildren>0 )
956
                       {
957
                       DistortedNode tmp;
958

    
959
                       for(int j=mNumChildren-1; j>=0; j--)
960
                         {
961
                         tmp = mChildren.remove(j);
962
                         tmp.setSurfaceParent(null);
963
                         }
964

    
965
                       mNumChildren = 0;
966
                       }
967
                     break;
968
        case SORT  : mChildren.remove(job.node);
969
                     DistortedMaster.addSorted(mChildren,job.node);
970
                     break;
971
        }
972
      }
973
    }
974
}
(8-8/21)