Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ cee0369a

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
  // Global buffers used for postprocessing.
83
  private static DistortedOutputSurface[] mBuffer = new DistortedOutputSurface[EffectQuality.LENGTH];
84

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

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

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

    
101
  private int mDebugLevel;
102

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

    
108
  ////////////////////////////////////////////////////////////////////////////////
109
  // section dealing with Shader Storage Buffer Object (for counting transparency)
110
  private static final int FRAME_DELAY = 3;
111
  private static int mBufferSize       =10;
112
  private static DistortedObjectCounter mSurfaceCounter = new DistortedObjectCounter();
113
  private static int[] mSSBO = new int[1];
114
  private static IntBuffer mIntBuffer;
115

    
116
  static
117
    {
118
    mSSBO[0]= -1;
119
    }
120

    
121
  private int mSurfaceID;
122
  private int mLastIndex;
123
  private int[] mLastValue = new int[FRAME_DELAY];
124
  private int mLastDiff = -1;
125

    
126
  private static final int RUNNING_AVERAGE = 10;
127
  private int[] mRunningAvg = new int[RUNNING_AVERAGE];
128
  private int mAvgIndex;
129
  private int mAvgSum;
130
  // end section
131
  ////////////////////////////////////////////////////////////////////////////////
132

    
133
///////////////////////////////////////////////////////////////////////////////////////////////////
134

    
135
  abstract void prepareDebug(long time);
136
  abstract void renderDebug(long time);
137
  abstract void createSurface();
138
  abstract void deleteSurface();
139
  abstract void recreateSurface();
140

    
141
///////////////////////////////////////////////////////////////////////////////////////////////////
142

    
143
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
144
    {
145
    super(width,height,createColor,numcolors,type);
146

    
147
    mRealWidth = width;
148
    mRealHeight= height;
149

    
150
    mProjectionMatrix = new float[16];
151

    
152
    mFOV = 60.0f;
153
    mNear=  0.5f;
154

    
155
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
156
    mDepthStencil = depthStencil;
157

    
158
    mFBOH[0]         = fbo;
159
    mDepthStencilH[0]= 0;
160

    
161
    mTime = 0;
162
    mDebugLevel = 0;
163

    
164
    mClearR = 0.0f;
165
    mClearG = 0.0f;
166
    mClearB = 0.0f;
167
    mClearA = 0.0f;
168

    
169
    mClearDepth = 1.0f;
170
    mClearStencil = 0;
171
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
172

    
173
    mMipmap = 1.0f;
174

    
175
    createProjection();
176
    }
177

    
178
///////////////////////////////////////////////////////////////////////////////////////////////////
179
// Must be called from a thread holding OpenGL Context
180

    
181
  void create()
182
    {
183
    if( mSSBO[0]<0 )
184
      {
185
      GLES31.glGenBuffers(1,mSSBO,0);
186

    
187
      // here bind the new SSBO and map it
188
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mSSBO[0]);
189
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, FRAME_DELAY *mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ);
190
      ByteBuffer buf = (ByteBuffer) GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, FRAME_DELAY *mBufferSize*4, GLES31.GL_MAP_READ_BIT );
191
      mIntBuffer = buf.order(ByteOrder.nativeOrder()).asIntBuffer();
192
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER,0, mSSBO[0]);
193
      }
194

    
195
    mSurfaceID = mSurfaceCounter.returnNext();
196

    
197
    if( mSurfaceID>=mBufferSize )
198
      {
199
      // increase size of the Buffer, copy over old values, remap.
200
      int[] tmp = new int[FRAME_DELAY *mBufferSize];
201
      for(int i = 0; i< FRAME_DELAY *mBufferSize; i++) tmp[i] = mIntBuffer.get(i);
202

    
203
      mBufferSize*= 2;
204

    
205
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0);
206
      GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER);
207
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER,0);
208

    
209
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mSSBO[0]);
210
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, FRAME_DELAY *mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ);
211
      ByteBuffer buf = (ByteBuffer) GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, FRAME_DELAY *mBufferSize*4, GLES31.GL_MAP_READ_BIT );
212
      mIntBuffer = buf.order(ByteOrder.nativeOrder()).asIntBuffer();
213
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER,0, mSSBO[0]);
214

    
215
      for(int i=0;i<tmp.length;i++) mIntBuffer.put(i,tmp[i]);
216
      }
217

    
218
    createSurface();
219
    }
220

    
221
///////////////////////////////////////////////////////////////////////////////////////////////////
222
// Must be called from a thread holding OpenGL Context
223

    
224
  void delete()
225
    {
226
    mSurfaceCounter.release(mSurfaceID);
227
    deleteSurface();
228
    }
229

    
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231

    
232
  void recreate()
233
    {
234
    mSSBO[0]  = -1;
235
    mLastDiff = -1;
236

    
237
    for(int i = 0; i< FRAME_DELAY; i++) mLastValue[i] = 0;
238
    mSurfaceCounter.releaseAll();
239

    
240
    recreateSurface();
241
    }
242

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

    
245
  int getNewCounter()
246
    {
247
    return FRAME_DELAY*mSurfaceID + mLastIndex;
248
    }
249

    
250
///////////////////////////////////////////////////////////////////////////////////////////////////
251

    
252
  private void createProjection()
253
    {
254
    if( mWidth>0 && mHeight>1 )
255
      {
256
      if( mFOV>0.0f )  // perspective projection
257
        {
258
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
259
        float q = mWidth*mNear;
260
        float c = mHeight*mNear;
261

    
262
        float left   = -q/2;
263
        float right  = +q/2;
264
        float bottom = -c/2;
265
        float top    = +c/2;
266
        float near   =  c/a;
267

    
268
        mDistance    = mHeight/a;
269
        float far    = 2*mDistance-near;
270

    
271
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
272
        }
273
      else             // parallel projection
274
        {
275
        float left   = -mWidth/2.0f;
276
        float right  = +mWidth/2.0f;
277
        float bottom = -mHeight/2.0f;
278
        float top    = +mHeight/2.0f;
279
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
280
        mDistance    = mWidth+mHeight;
281
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
282

    
283
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
284
        }
285
      }
286
    }
287

    
288
///////////////////////////////////////////////////////////////////////////////////////////////////
289

    
290
  private static void createBuffers(int width, int height, float near)
291
    {
292
    float mipmap=1.0f;
293

    
294
    for(int j=0; j<EffectQuality.LENGTH; j++)
295
      {
296
      mBuffer[j] = new DistortedFramebuffer(2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
297
      mBuffer[j].mMipmap = mipmap;
298
      mBuffer[j].mNear   = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
299
      mBuffer[j].glClearColor(1.0f,1.0f,1.0f,0.0f);
300

    
301
      mipmap *= EffectQuality.MULTIPLIER;
302
      }
303

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

    
306
    GLES31.glStencilMask(0xff);
307
    GLES31.glDepthMask(true);
308
    GLES31.glColorMask(true,true,true,true);
309
    GLES31.glClearColor(1.0f,1.0f,1.0f,0.0f);
310
    GLES31.glClearDepthf(1.0f);
311
    GLES31.glClearStencil(0);
312

    
313
    for(int j=0; j<EffectQuality.LENGTH; j++)
314
      {
315
      mBuffer[j].setAsOutput();
316
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
317
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
318
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
319
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
320
      }
321
    }
322

    
323
///////////////////////////////////////////////////////////////////////////////////////////////////
324

    
325
  static synchronized void onDestroy()
326
    {
327
    for(int j=0; j<EffectQuality.LENGTH; j++)
328
      {
329
      mBuffer[j] = null;
330
      }
331
    }
332

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

    
339
  private static void cloneViewport(DistortedOutputSurface from)
340
    {
341
    if( mBuffer[0].mWidth != from.mWidth )
342
      {
343
      DistortedOutputSurface surface;
344

    
345
      for(int i=0; i<EffectQuality.LENGTH; i++)
346
        {
347
        surface = mBuffer[i];
348

    
349
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
350
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
351

    
352
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
353

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

    
356
        surface.createProjection();
357

    
358
        int maxw = surface.mWidth  > surface.mRealWidth  ? surface.mWidth  : surface.mRealWidth;
359
        int maxh = surface.mHeight > surface.mRealHeight ? surface.mHeight : surface.mRealHeight;
360

    
361
        if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
362
          {
363
          surface.mRealWidth = maxw;
364
          surface.mRealHeight = maxh;
365

    
366
          surface.recreateSurface();
367
          surface.createSurface();
368
          }
369
        }
370
      }
371
    }
372

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374

    
375
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer)
376
    {
377
    GLES31.glViewport(0, 0, mWidth, mHeight);
378
    setAsOutput(currTime);
379
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
380
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[0]);
381
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
382
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
383

    
384
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
385
    GLES31.glStencilMask(0x00);
386

    
387
    DistortedEffects.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
388
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
389
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
390
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
391
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
392

    
393
    return 1;
394
    }
395

    
396
///////////////////////////////////////////////////////////////////////////////////////////////////
397

    
398
  private int blitWithDepthRender(long currTime, DistortedOutputSurface buffer)
399
    {
400
    GLES31.glViewport(0, 0, mWidth, mHeight);
401
    setAsOutput(currTime);
402
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
403
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
404

    
405
    DistortedRenderState.enableStencil();
406

    
407
    DistortedEffects.blitDepthRenderPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
408
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
409
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
410

    
411
    DistortedRenderState.restoreStencil();
412

    
413
    return 1;
414
    }
415

    
416
///////////////////////////////////////////////////////////////////////////////////////////////////
417

    
418
  private void clearBuffer(DistortedOutputSurface buffer)
419
    {
420
    GLES31.glStencilMask(0xff);
421
    GLES31.glDepthMask(true);
422
    GLES31.glColorMask(true,true,true,true);
423
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
424
    GLES31.glClearDepthf(1.0f);
425
    GLES31.glClearStencil(0);
426

    
427
    buffer.setAsOutput();
428
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[1], 0);
429
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
430
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[0], 0);
431
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
432
    }
433

    
434
///////////////////////////////////////////////////////////////////////////////////////////////////
435
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
436
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
437
// to a whole buffer (lastQueue.postprocess) and merge it (this.blitWithDepth).
438

    
439
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
440
    {
441
    int quality=0, internalQuality = 0, numRenders = 0, bucketChange = 0;
442
    DistortedNode child1, child2;
443
    EffectQueuePostprocess lastQueue=null, currQueue;
444
    long lastBucket=0, currBucket;
445

    
446
    for(int i=0; i<numChildren; i++)
447
      {
448
      child1 = children.get(i);
449
      currQueue = child1.getPostprocessQueue();
450
      currBucket= currQueue.getID();
451

    
452
      if( currBucket==0 ) numRenders += child1.draw(time,this);
453
      else
454
        {
455
        if( mBuffer[0]==null ) createBuffers(mWidth,mHeight,mNear);
456

    
457
        if( lastBucket!=currBucket )
458
          {
459
          if( lastBucket!=0 )
460
            {
461
            for(int j=bucketChange; j<i; j++)
462
              {
463
              child2 = children.get(j);
464
              numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],lastQueue);
465
              }
466

    
467
            numRenders += lastQueue.postprocess(mBuffer);
468
            numRenders += blitWithDepth(time, mBuffer[quality]);
469
            clearBuffer(mBuffer[quality]);
470
            }
471

    
472
          internalQuality = currQueue.getInternalQuality();
473
          quality         = currQueue.getQuality();
474
          bucketChange    = i;
475

    
476
          cloneViewport(this);
477
          }
478

    
479
        child1.drawNoBlend(time,mBuffer[quality]);
480

    
481
        if( i==numChildren-1 )
482
          {
483
          for(int j=bucketChange; j<numChildren; j++)
484
            {
485
            child2 = children.get(j);
486
            numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],currQueue);
487
            }
488

    
489
          numRenders += currQueue.postprocess(mBuffer);
490
          numRenders += blitWithDepth(time, mBuffer[quality]);
491
          GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS);
492
          //GLES31.glFinish();
493
          numRenders += blitWithDepthRender(time,mBuffer[quality]);  // merge the OIT linked list
494
          clearBuffer(mBuffer[quality]);
495
          GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS);
496
          //GLES31.glFlush();
497
          }
498
        }
499

    
500
      lastQueue = currQueue;
501
      lastBucket= currBucket;
502
      }
503

    
504
    return numRenders;
505
    }
506

    
507
///////////////////////////////////////////////////////////////////////////////////////////////////
508

    
509
  ArrayList<DistortedNode> getChildren()
510
    {
511
    return mChildren;
512
    }
513

    
514
///////////////////////////////////////////////////////////////////////////////////////////////////
515
/**
516
 * Not part of the Public API.
517
 *
518
 * @y.exclude
519
 */
520
  public float getWidthCorrection()
521
    {
522
    return (float)mWidth/mRealWidth;
523
    }
524

    
525
///////////////////////////////////////////////////////////////////////////////////////////////////
526
/**
527
 * Not part of the Public API.
528
 *
529
 * @y.exclude
530
 */
531
  public float getHeightCorrection()
532
    {
533
    return (float)mHeight/mRealHeight;
534
    }
535

    
536
///////////////////////////////////////////////////////////////////////////////////////////////////
537
// PUBLIC API
538
///////////////////////////////////////////////////////////////////////////////////////////////////
539
/**
540
 * Make the library show various debugging information.
541
 * <p>
542
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
543
 *
544
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
545
 */
546
  public void setDebug(int bitmask)
547
    {
548
    if( this instanceof DistortedScreen )
549
      mDebugLevel = bitmask;
550
    }
551

    
552
///////////////////////////////////////////////////////////////////////////////////////////////////
553

    
554
/**
555
 * Draws all the attached children to this OutputSurface.
556
 * <p>
557
 * Must be called from a thread holding OpenGL Context.
558
 *
559
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
560
 * @return Number of objects rendered.
561
 */
562
  public int render(long time)
563
    {
564
    if( mDebugLevel!=0 ) prepareDebug(time);
565

    
566
    // change tree topology (attach and detach children)
567
/*
568
    boolean changed1 =
569
*/
570
    DistortedMaster.toDo();
571
/*
572
    if( changed1 )
573
      {
574
      for(int i=0; i<mNumChildren; i++)
575
        {
576
        mChildren.get(i).debug(0);
577
        }
578

    
579
      DistortedNode.debugMap();
580
      }
581
*/
582
    // create and delete all underlying OpenGL resources
583
    // Watch out: FIRST change topology, only then deal
584
    // with OpenGL resources. That's because changing Tree
585
    // can result in additional Framebuffers that would need
586
    // to be created immediately, before the calls to drawRecursive()
587
/*
588
    boolean changed2 =
589
*/
590
    toDo();
591
/*
592
    if( changed2 )
593
      {
594
      DistortedObject.debugLists();
595
      }
596
*/
597
    // mark OpenGL state as unknown
598
    DistortedRenderState.reset();
599

    
600
    int numRenders=0;
601

    
602
    for(int i=0; i<mNumChildren; i++)
603
      {
604
      numRenders += mChildren.get(i).renderRecursive(time);
605
      }
606

    
607
    setAsOutput(time);
608
    numRenders += renderChildren(time,mNumChildren,mChildren);
609

    
610
    if( mDebugLevel != 0 ) renderDebug(time);
611

    
612
    return numRenders;
613
    }
614

    
615
///////////////////////////////////////////////////////////////////////////////////////////////////
616
/**
617
 * Bind this Surface as a Framebuffer we can render to.
618
 *
619
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
620
 *             out if this is the first time during present frame that this FBO is being set as output.
621
 *             If so, the library, in addition to binding the Surface for output, also clears the
622
 *             Surface's color and depth attachments.
623
 */
624
  public void setAsOutput(long time)
625
    {
626
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
627

    
628
    if( mTime!=time )
629
      {
630
      mTime = time;
631
      DistortedRenderState.colorDepthStencilOn();
632
      GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
633
      GLES31.glClearDepthf(mClearDepth);
634
      GLES31.glClearStencil(mClearStencil);
635
      GLES31.glClear(mClear);
636
      DistortedRenderState.colorDepthStencilRestore();
637
/*
638
      if( mSSBO[0]>=0 )
639
        {
640
        // yes, this DOES keep on working when 'value' overflows into negative territory.
641
        int value = mIntBuffer.get(FRAME_DELAY*mSurfaceID+mLastIndex);
642

    
643
        if( value-mLastValue[mLastIndex]!=mLastDiff )
644
          {
645
          android.util.Log.d("surface", "id " + mSurfaceID +
646
                             (mType == TYPE_USER ? " USER" : (mType == TYPE_SYST ? " SYST" : " TREE")) +
647
                             " viewport: (" + mWidth + "x" + mHeight + ") last frame: " + (value - mLastValue[mLastIndex])
648
                             + " avg: " + (mAvgSum/RUNNING_AVERAGE)
649
                            );
650
          }
651

    
652
        mLastDiff = value-mLastValue[mLastIndex];
653
        mLastValue[mLastIndex] = value;
654

    
655
        mAvgSum += (mLastDiff-mRunningAvg[mAvgIndex]);
656
        mRunningAvg[mAvgIndex] = mLastDiff;
657
        if( ++mAvgIndex>=RUNNING_AVERAGE ) mAvgIndex =0;
658
        }
659

    
660
      if( ++mLastIndex >= FRAME_DELAY ) mLastIndex=0;
661
*/
662
      }
663
    }
664

    
665
///////////////////////////////////////////////////////////////////////////////////////////////////
666
/**
667
 * Bind this Surface as a Framebuffer we can render to.
668
 * <p>
669
 * This version does not attempt to clear anything.
670
 */
671

    
672
  public void setAsOutput()
673
    {
674
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
675
    }
676

    
677
///////////////////////////////////////////////////////////////////////////////////////////////////
678
/**
679
 * Return the Near plane of the Projection included in the Surface.
680
 *
681
 * @return the Near plane.
682
 */
683
  public float getNear()
684
    {
685
    return mNear;
686
    }
687

    
688
///////////////////////////////////////////////////////////////////////////////////////////////////
689
/**
690
 * Set mipmap level.
691
 * <p>
692
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
693
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
694
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
695
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
696
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
697
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
698
 * <p>
699
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
700
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
701
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
702
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
703
 *
704
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
705
 *               does not make any sense (that would result in loss of speed and no gain in quality)
706
 */
707
  public void setMipmap(float mipmap)
708
    {
709
    mMipmap = mipmap;
710
    }
711

    
712
///////////////////////////////////////////////////////////////////////////////////////////////////
713
/**
714
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
715
 * this Surface at the beginning of each frame.
716
 *
717
 * @param r the Red component. Default: 0.0f
718
 * @param g the Green component. Default: 0.0f
719
 * @param b the Blue component. Default: 0.0f
720
 * @param a the Alpha component. Default: 0.0f
721
 */
722
  public void glClearColor(float r, float g, float b, float a)
723
    {
724
    mClearR = r;
725
    mClearG = g;
726
    mClearB = b;
727
    mClearA = a;
728
    }
729

    
730
///////////////////////////////////////////////////////////////////////////////////////////////////
731
/**
732
 * Uses glClearDepthf() to set up a value with which to clear
733
 * the Depth buffer of our Surface at the beginning of each frame.
734
 *
735
 * @param d the Depth. Default: 1.0f
736
 */
737
  public void glClearDepthf(float d)
738
    {
739
    mClearDepth = d;
740
    }
741

    
742
///////////////////////////////////////////////////////////////////////////////////////////////////
743
/**
744
 * Uses glClearStencil() to set up a value with which to clear the
745
 * Stencil buffer of our Surface at the beginning of each frame.
746
 *
747
 * @param s the Stencil. Default: 0
748
 */
749
  public void glClearStencil(int s)
750
    {
751
    mClearStencil = s;
752
    }
753

    
754
///////////////////////////////////////////////////////////////////////////////////////////////////
755
/**
756
 * Which buffers to Clear at the beginning of each frame?
757
 * <p>
758
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
759
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
760
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
761
 *
762
 * @param mask bitwise OR of BUFFER_BITs to clear.
763
 */
764
  public void glClear(int mask)
765
    {
766
    mClear = mask;
767
    }
768

    
769
///////////////////////////////////////////////////////////////////////////////////////////////////
770
/**
771
 * Create new Projection matrix.
772
 *
773
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
774
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
775
 * @param near Distance between the screen plane and the near plane.
776
 *             Valid vaules: 0<near<1. When near==0 (illegal!), the Near Plane is exactly at the tip of
777
 *             the pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
778
 */
779
  public void setProjection(float fov, float near)
780
    {
781
    if( fov < 180.0f && fov >=0.0f )
782
      {
783
      mFOV = fov;
784
      }
785

    
786
    if( near<   1.0f && near> 0.0f )
787
      {
788
      mNear= near;
789
      }
790
    else if( near<=0.0f )
791
      {
792
      mNear = 0.01f;
793
      }
794
    else if( near>=1.0f )
795
      {
796
      mNear=0.99f;
797
      }
798

    
799
    if( mBuffer[0]!=null )
800
      {
801
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
802
      }
803

    
804
    createProjection();
805
    }
806

    
807
///////////////////////////////////////////////////////////////////////////////////////////////////
808
/**
809
 * Resize the underlying Framebuffer.
810
 * <p>
811
 * This method can be safely called mid-render as it doesn't interfere with rendering.
812
 *
813
 * @param width The new width.
814
 * @param height The new height.
815
 */
816
  public void resize(int width, int height)
817
    {
818
    if( mWidth!=width || mHeight!=height )
819
      {
820
      mWidth = mRealWidth = width;
821
      mHeight= mRealHeight= height;
822

    
823
      createProjection();
824

    
825
      if( mColorCreated==CREATED )
826
        {
827
        markForCreation();
828
        recreate();
829
        }
830
      }
831
    }
832

    
833
///////////////////////////////////////////////////////////////////////////////////////////////////
834
/**
835
 * Return true if the Surface contains a DEPTH attachment.
836
 *
837
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
838
 */
839
  public boolean hasDepth()
840
    {
841
    return mDepthStencilCreated==CREATED;
842
    }
843

    
844
///////////////////////////////////////////////////////////////////////////////////////////////////
845
/**
846
 * Return true if the Surface contains a STENCIL attachment.
847
 *
848
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
849
 */
850
  public boolean hasStencil()
851
    {
852
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
853
    }
854

    
855
///////////////////////////////////////////////////////////////////////////////////////////////////
856
/**
857
 * Adds a new child to the last position in the list of our Surface's children.
858
 * <p>
859
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
860
 * DistortedMaster (by calling doWork())
861
 *
862
 * @param node The new Node to add.
863
 */
864
  public void attach(DistortedNode node)
865
    {
866
    mJobs.add(new Job(ATTACH,node));
867
    DistortedMaster.newSlave(this);
868
    }
869

    
870
///////////////////////////////////////////////////////////////////////////////////////////////////
871
/**
872
 * Adds a new child to the last position in the list of our Surface's children.
873
 * <p>
874
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
875
 * DistortedMaster (by calling doWork())
876
 *
877
 * @param surface InputSurface to initialize our child Node with.
878
 * @param effects DistortedEffects to initialize our child Node with.
879
 * @param mesh MeshObject to initialize our child Node with.
880
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
881
 */
882
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
883
    {
884
    DistortedNode node = new DistortedNode(surface,effects,mesh);
885
    mJobs.add(new Job(ATTACH,node));
886
    DistortedMaster.newSlave(this);
887
    return node;
888
    }
889

    
890
///////////////////////////////////////////////////////////////////////////////////////////////////
891
/**
892
 * Removes the first occurrence of a specified child from the list of children of our Surface.
893
 * <p>
894
 * A bit questionable method as there can be many different Nodes attached as children, some
895
 * of them having the same Effects but - for instance - different Mesh. Use with care.
896
 * <p>
897
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
898
 * DistortedMaster (by calling doWork())
899
 *
900
 * @param effects DistortedEffects to remove.
901
 */
902
  public void detach(DistortedEffects effects)
903
    {
904
    long id = effects.getID();
905
    DistortedNode node;
906
    boolean detached = false;
907

    
908
    for(int i=0; i<mNumChildren; i++)
909
      {
910
      node = mChildren.get(i);
911

    
912
      if( node.getEffects().getID()==id )
913
        {
914
        detached = true;
915
        mJobs.add(new Job(DETACH,node));
916
        DistortedMaster.newSlave(this);
917
        break;
918
        }
919
      }
920

    
921
    if( !detached )
922
      {
923
      // if we failed to detach any, it still might be the case that
924
      // there's an ATTACH job that we need to cancel.
925
      int num = mJobs.size();
926
      Job job;
927

    
928
      for(int i=0; i<num; i++)
929
        {
930
        job = mJobs.get(i);
931

    
932
        if( job.type==ATTACH && job.node.getEffects()==effects )
933
          {
934
          mJobs.remove(i);
935
          break;
936
          }
937
        }
938
      }
939
    }
940

    
941
///////////////////////////////////////////////////////////////////////////////////////////////////
942
/**
943
 * Removes the first occurrence of a specified child from the list of children of our Surface.
944
 * <p>
945
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
946
 * DistortedMaster (by calling doWork())
947
 *
948
 * @param node The Node to remove.
949
 */
950
  public void detach(DistortedNode node)
951
    {
952
    mJobs.add(new Job(DETACH,node));
953
    DistortedMaster.newSlave(this);
954
    }
955

    
956
///////////////////////////////////////////////////////////////////////////////////////////////////
957
/**
958
 * Removes all children Nodes.
959
 * <p>
960
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
961
 * DistortedMaster (by calling doWork())
962
 */
963
  public void detachAll()
964
    {
965
    mJobs.add(new Job(DETALL,null));
966
    DistortedMaster.newSlave(this);
967
    }
968

    
969
///////////////////////////////////////////////////////////////////////////////////////////////////
970
/**
971
 * This is not really part of the public API. Has to be public only because it is a part of the
972
 * DistortedSlave interface, which should really be a class that we extend here instead but
973
 * Java has no multiple inheritance.
974
 *
975
 * @y.exclude
976
 */
977
  public void doWork()
978
    {
979
    int num = mJobs.size();
980
    Job job;
981

    
982
    for(int i=0; i<num; i++)
983
      {
984
      job = mJobs.remove(0);
985

    
986
      switch(job.type)
987
        {
988
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
989
                     job.node.setSurfaceParent(this);
990
                     DistortedMaster.addSorted(mChildren,job.node);
991
                     mNumChildren++;
992
                     break;
993
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
994
                       {
995
                       job.node.setSurfaceParent(null);
996
                       mNumChildren--;
997
                       }
998
                     break;
999
        case DETALL: if( mNumChildren>0 )
1000
                       {
1001
                       DistortedNode tmp;
1002

    
1003
                       for(int j=mNumChildren-1; j>=0; j--)
1004
                         {
1005
                         tmp = mChildren.remove(j);
1006
                         tmp.setSurfaceParent(null);
1007
                         }
1008

    
1009
                       mNumChildren = 0;
1010
                       }
1011
                     break;
1012
        case SORT  : mChildren.remove(job.node);
1013
                     DistortedMaster.addSorted(mChildren,job.node);
1014
                     break;
1015
        }
1016
      }
1017
    }
1018
}
(9-9/22)