Project

General

Profile

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

library / src / main / java / org / distorted / library / main / InternalOutputSurface.java @ d58b50e7

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
import org.distorted.library.effectqueue.EffectQueuePostprocess;
27
import org.distorted.library.mesh.MeshBase;
28

    
29
///////////////////////////////////////////////////////////////////////////////////////////////////
30
/**
31
 * This is not really part of the public API.
32
 *
33
 * @y.exclude
34
 */
35
public abstract class InternalOutputSurface extends InternalSurface implements InternalChildrenList.Parent
36
{
37
  public static final int NO_DEPTH_NO_STENCIL = 0;
38
  public static final int DEPTH_NO_STENCIL    = 1;
39
  public static final int BOTH_DEPTH_STENCIL  = 2;
40

    
41
  float mFOV, mDistance, mNear, mMipmap;
42
  float[] mProjectionMatrix;
43
  int mDepthStencilCreated, mDepthStencil;
44
  int[] mDepthStencilH, mFBOH;
45
  int mRealWidth;   // the Surface can be backed up by a texture larger than the viewport we have to it.
46
  int mRealHeight;  // mWidth,mHeight are the sizes of the Viewport, those - sizes of the backing up texture.
47
  int mCurrFBO;     // internal current FBO (see DistortedLibrary.FBO_QUEUE_SIZE)
48
  int mWidth, mHeight;
49

    
50
  private static DistortedFramebuffer[] mBuffer=null; // Global buffers used for postprocessing.
51
  private long[] mTime;
52
  private float mClearR, mClearG, mClearB, mClearA, mClearDepth;
53
  private int mClear, mClearStencil;
54
  private boolean mRenderWayOIT;
55
  private InternalChildrenList mChildren;
56

    
57
///////////////////////////////////////////////////////////////////////////////////////////////////
58

    
59
  InternalOutputSurface(int width, int height, int createColor, int numfbos, int numcolors, int depthStencil, int fbo, int type)
60
    {
61
    super(createColor,numfbos,numcolors,type);
62

    
63
    mRenderWayOIT = false;
64
    mCurrFBO      = 0;
65

    
66
    mDepthStencilH = new int[numfbos];
67
    mFBOH          = new int[numfbos];
68

    
69
    mTime = new long[numfbos];
70
    for(int i=0; i<mNumFBOs;i++) mTime[i]=0;
71

    
72
    mRealWidth = mWidth = width;
73
    mRealHeight= mHeight= height;
74

    
75
    mProjectionMatrix = new float[16];
76

    
77
    mFOV = 60.0f;
78
    mNear=  0.5f;
79

    
80
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
81
    mDepthStencil = depthStencil;
82

    
83
    mFBOH[0]         = fbo;
84
    mDepthStencilH[0]= 0;
85

    
86
    mClearR = 0.0f;
87
    mClearG = 0.0f;
88
    mClearB = 0.0f;
89
    mClearA = 0.0f;
90

    
91
    mClearDepth = 1.0f;
92
    mClearStencil = 0;
93
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
94

    
95
    mMipmap = 1.0f;
96

    
97
    mChildren = new InternalChildrenList(this);
98

    
99
    createProjection();
100
    }
101

    
102
///////////////////////////////////////////////////////////////////////////////////////////////////
103

    
104
  private void createProjection()
105
    {
106
    if( mWidth>0 && mHeight>1 )
107
      {
108
      if( mFOV>0.0f )  // perspective projection
109
        {
110
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
111
        float q = mWidth*mNear;
112
        float c = mHeight*mNear;
113

    
114
        float left   = -q/2;
115
        float right  = +q/2;
116
        float bottom = -c/2;
117
        float top    = +c/2;
118
        float near   =  c/a;
119

    
120
        mDistance    = mHeight/a;
121
        float far    = 2*mDistance-near;
122

    
123
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
124
        }
125
      else             // parallel projection
126
        {
127
        float left   = -mWidth/2.0f;
128
        float right  = +mWidth/2.0f;
129
        float bottom = -mHeight/2.0f;
130
        float top    = +mHeight/2.0f;
131
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
132
        mDistance    = mWidth+mHeight;
133
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
134

    
135
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
136
        }
137
      }
138
    }
139

    
140
///////////////////////////////////////////////////////////////////////////////////////////////////
141

    
142
  private static void createPostprocessingBuffers(int width, int height, float near)
143
    {
144
    final float CLEAR_R = 1.0f;
145
    final float CLEAR_G = 1.0f;
146
    final float CLEAR_B = 1.0f;
147
    final float CLEAR_A = 0.0f;
148
    final float CLEAR_D = 1.0f;
149
    final int   CLEAR_S = 0;
150

    
151
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
152
    float mipmap=1.0f;
153

    
154
    for (int j=0; j<EffectQuality.LENGTH; j++)
155
      {
156
      mBuffer[j] = new DistortedFramebuffer(DistortedLibrary.FBO_QUEUE_SIZE,2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
157
      mBuffer[j].mMipmap = mipmap;
158
      mBuffer[j].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
159
      mBuffer[j].glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
160

    
161
      mipmap *= EffectQuality.MULTIPLIER;
162
      }
163

    
164
    InternalObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
165

    
166
    InternalRenderState.colorDepthStencilOn();
167
    GLES31.glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
168
    GLES31.glClearDepthf(CLEAR_D);
169
    GLES31.glClearStencil(CLEAR_S);
170

    
171
    for (int j=0; j<EffectQuality.LENGTH; j++)
172
      {
173
      for(int k = 0; k< DistortedLibrary.FBO_QUEUE_SIZE; k++)
174
        {
175
        GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBuffer[j].mFBOH[k]);
176
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k+1], 0);
177
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_STENCIL_BUFFER_BIT);
178
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k  ], 0);
179
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
180
        }
181
      }
182

    
183
    InternalRenderState.colorDepthStencilRestore();
184

    
185
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
186
    }
187

    
188
///////////////////////////////////////////////////////////////////////////////////////////////////
189

    
190
  static synchronized void onDestroy()
191
    {
192
    if( mBuffer!=null )
193
      {
194
      for (int j = 0; j < EffectQuality.LENGTH; j++)
195
        {
196
        mBuffer[j] = null;
197
        }
198

    
199
      mBuffer = null;
200
      }
201
    }
202

    
203
///////////////////////////////////////////////////////////////////////////////////////////////////
204
// The postprocessing buffers mBuffer[] are generally speaking too large (there's just one static
205
// set of them) so before we use them for output, we need to adjust the Viewport as if they were
206
// smaller. That takes care of outputting pixels to them. When we use them as input, we have to
207
// adjust the texture coords - see the get{Width|Height}Correction functions.
208
//
209
// Also, adjust the Buffers so their Projection is the same like the surface we are supposed to be
210
// rendering to.
211

    
212
  private static void clonePostprocessingViewportAndProjection(InternalOutputSurface from)
213
    {
214
    if( mBuffer[0].mWidth != from.mWidth || mBuffer[0].mHeight != from.mHeight ||
215
        mBuffer[0].mFOV   != from.mFOV   || mBuffer[0].mNear   != from.mNear    )
216
      {
217
      InternalOutputSurface surface;
218

    
219
      for(int i=0; i<EffectQuality.LENGTH; i++)
220
        {
221
        surface = mBuffer[i];
222

    
223
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
224
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
225
        surface.mFOV    = from.mFOV;
226
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
227

    
228
        surface.createProjection();
229

    
230
        int maxw = surface.mWidth  > surface.mRealWidth  ? surface.mWidth  : surface.mRealWidth;
231
        int maxh = surface.mHeight > surface.mRealHeight ? surface.mHeight : surface.mRealHeight;
232

    
233
        if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
234
          {
235
          surface.mRealWidth = maxw;
236
          surface.mRealHeight = maxh;
237

    
238
          surface.recreate();
239
          surface.create();
240
          }
241
        }
242
      }
243
    }
244

    
245
///////////////////////////////////////////////////////////////////////////////////////////////////
246

    
247
  private int blitWithDepth(long currTime, InternalOutputSurface buffer, int fbo)
248
    {
249
    GLES31.glViewport(0, 0, mWidth, mHeight);
250
    setAsOutput(currTime);
251
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
252
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
253
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
254
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
255

    
256
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
257
    GLES31.glStencilMask(0x00);
258

    
259
    DistortedLibrary.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
260
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
261
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
262
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
263
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
264

    
265
    // clear buffers
266
    GLES31.glStencilMask(0xff);
267
    GLES31.glDepthMask(true);
268
    GLES31.glColorMask(true,true,true,true);
269
    GLES31.glClearColor(buffer.mClearR,buffer.mClearG,buffer.mClearB,buffer.mClearA);
270
    GLES31.glClearDepthf(buffer.mClearDepth);
271
    GLES31.glClearStencil(buffer.mClearStencil);
272

    
273
    buffer.setAsOutput();
274
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
275
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
276
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
277
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
278

    
279
    return 1;
280
    }
281

    
282
///////////////////////////////////////////////////////////////////////////////////////////////////
283

    
284
  private static void oitClear(InternalOutputSurface buffer)
285
    {
286
    int counter = DistortedLibrary.zeroOutAtomic();
287
    DistortedLibrary.oitClear(buffer,counter);
288
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
289
    }
290

    
291
///////////////////////////////////////////////////////////////////////////////////////////////////
292

    
293
  private int oitBuild(long time, InternalOutputSurface buffer, int fbo)
294
    {
295
    GLES31.glViewport(0, 0, mWidth, mHeight);
296
    setAsOutput(time);
297
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
298
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
299
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
300
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
301

    
302
    InternalRenderState.colorDepthStencilOn();
303
    InternalRenderState.enableDepthTest();
304

    
305
    DistortedLibrary.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
306
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
307
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
308
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
309
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
310

    
311
    InternalRenderState.colorDepthStencilRestore();
312
    InternalRenderState.restoreDepthTest();
313

    
314
    return 1;
315
    }
316

    
317
///////////////////////////////////////////////////////////////////////////////////////////////////
318
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
319

    
320
  private int oitRender(long currTime, int fbo)
321
    {
322
    float corrW = getWidthCorrection();
323
    float corrH = getHeightCorrection();
324

    
325
    // Do the Collapse Pass only if we do have a Depth attachment.
326
    // Otherwise there's no point (in fact we then would create a feedback loop!)
327

    
328
    if( mDepthStencilH[fbo] != 0 )
329
      {
330
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
331
      GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
332
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, mDepthStencilH[fbo]);
333
      InternalRenderState.switchOffColorDepthStencil();
334
      DistortedLibrary.oitCollapse(this, corrW, corrH);
335
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
336
      }
337

    
338
    setAsOutput(currTime);
339
    InternalRenderState.switchColorDepthOnStencilOff();
340
    DistortedLibrary.oitRender(this, corrW, corrH);
341
    InternalRenderState.restoreColorDepthStencil();
342

    
343
    return 1;
344
    }
345

    
346
///////////////////////////////////////////////////////////////////////////////////////////////////
347

    
348
  private void clear()
349
    {
350
    InternalRenderState.colorDepthStencilOn();
351
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
352
    GLES31.glClearDepthf(mClearDepth);
353
    GLES31.glClearStencil(mClearStencil);
354
    GLES31.glClear(mClear);
355
    InternalRenderState.colorDepthStencilRestore();
356
    }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359

    
360
  void setCurrFBO(int fbo)
361
    {
362
    mCurrFBO = fbo;
363
    }
364

    
365
///////////////////////////////////////////////////////////////////////////////////////////////////
366
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
367
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
368
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild or blitWithDepth - depending
369
// on the type of rendering)
370

    
371
  int renderChildren(long time, int numChildren, InternalChildrenList children, int fbo, boolean oit)
372
    {
373
    int numRenders=0, bucketChange=0;
374
    DistortedNode child;
375
    DistortedFramebuffer buffer=null;
376
    EffectQueuePostprocess lastQueue=null, currQueue;
377
    long lastBucket=0, currBucket;
378
    boolean renderDirectly=false;
379

    
380
    setCurrFBO(fbo);
381

    
382
    if( mBuffer!=null )
383
      {
384
      for (int i=0; i<EffectQuality.LENGTH; i++) mBuffer[i].setCurrFBO(fbo);
385
      }
386

    
387
    if( oit && numChildren>0 )
388
      {
389
      oitClear(this);
390
      }
391

    
392
    for(int i=0; i<numChildren; i++)
393
      {
394
      child = children.getChild(i);
395
      currQueue = (EffectQueuePostprocess)child.getEffects().getQueues()[3];
396
      currBucket= currQueue.getID();
397

    
398
      if( currBucket==0 )
399
        {
400
        setAsOutput(time);
401

    
402
        if( oit )
403
          {
404
          numRenders += child.drawOIT(time, this);
405
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
406
          }
407
        else
408
          {
409
          numRenders += child.draw(time, this);
410
          }
411
        }
412
      else
413
        {
414
        if( mBuffer==null )
415
          {
416
          createPostprocessingBuffers(mWidth,mHeight,mNear);
417
          for (int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].setCurrFBO(fbo);
418
          }
419

    
420
        if( lastBucket!=currBucket )
421
          {
422
          if( lastBucket==0 )
423
            {
424
            clonePostprocessingViewportAndProjection(this);
425
            }
426
          else
427
            {
428
            for(int j=bucketChange; j<i; j++)
429
              {
430
              DistortedNode node = children.getChild(j);
431

    
432
              if( node.getSurface().setAsInput() )
433
                {
434
                buffer.setAsOutput();
435
                numRenders += lastQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
436
                }
437
              }
438
            numRenders += lastQueue.postprocess(buffer);
439

    
440
            if( oit )
441
              {
442
              numRenders += oitBuild(time, buffer, fbo);
443
              GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
444
              }
445
            else
446
              {
447
              numRenders += blitWithDepth(time, buffer, fbo);
448
              }
449
            buffer.clearBuffer(fbo);
450
            }
451

    
452
          buffer= mBuffer[currQueue.getQuality()];
453
          bucketChange= i;
454
          renderDirectly = currQueue.getRender();
455
          }
456

    
457
        if( renderDirectly )
458
          {
459
          setAsOutput(time);
460

    
461
          if( oit )
462
            {
463
            numRenders += child.drawOIT(time, this);
464
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
465
            }
466
          else
467
            {
468
            numRenders += child.draw(time, this);
469
            }
470
          }
471
        else
472
          {
473
          buffer.setAsOutput(time);
474
          child.drawNoBlend(time, buffer);
475
          }
476

    
477
        if( i==numChildren-1 )
478
          {
479
          for(int j=bucketChange; j<numChildren; j++)
480
            {
481
            DistortedNode node = children.getChild(j);
482

    
483
            if( node.getSurface().setAsInput() )
484
              {
485
              buffer.setAsOutput();
486
              numRenders += currQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
487
              }
488
            }
489
          numRenders += currQueue.postprocess(buffer);
490

    
491
          if( oit )
492
            {
493
            numRenders += oitBuild(time, buffer, fbo);
494
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
495
            buffer.clearBuffer(fbo);
496
            }
497
          else
498
            {
499
            numRenders += blitWithDepth(time, buffer,fbo);
500
            }
501
          }
502
        } // end else (postprocessed child)
503

    
504
      lastQueue = currQueue;
505
      lastBucket= currBucket;
506
      } // end main for loop
507

    
508
    if( oit && numChildren>0 )
509
      {
510
      numRenders += oitRender(time, fbo);  // merge the OIT linked list
511
      }
512

    
513
    return numRenders;
514
    }
515

    
516
///////////////////////////////////////////////////////////////////////////////////////////////////
517
/**
518
 * Not part of the public API.
519
 *
520
 * @y.exclude
521
 */
522
  public void adjustIsomorphism() { }
523

    
524
///////////////////////////////////////////////////////////////////////////////////////////////////
525
/**
526
 * Not part of the Public API.
527
 *
528
 * @y.exclude
529
 */
530
  public float getWidthCorrection()
531
    {
532
    return (float)mWidth/mRealWidth;
533
    }
534

    
535
///////////////////////////////////////////////////////////////////////////////////////////////////
536
/**
537
 * Not part of the Public API.
538
 *
539
 * @y.exclude
540
 */
541
  public float getHeightCorrection()
542
    {
543
    return (float)mHeight/mRealHeight;
544
    }
545

    
546
///////////////////////////////////////////////////////////////////////////////////////////////////
547

    
548
  void clearBuffer(int fbo)
549
    {
550
    InternalRenderState.colorDepthStencilOn();
551

    
552
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
553
    GLES31.glClearDepthf(mClearDepth);
554
    GLES31.glClearStencil(mClearStencil);
555

    
556
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[fbo]);
557
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
558
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
559
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
560
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
561

    
562
    InternalRenderState.colorDepthStencilRestore();
563
    }
564

    
565
///////////////////////////////////////////////////////////////////////////////////////////////////
566

    
567
  void setAsOutput(long time)
568
    {
569
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
570

    
571
    if( mTime[mCurrFBO]!=time )
572
      {
573
      mTime[mCurrFBO] = time;
574
      clear();
575
      }
576
    }
577

    
578
///////////////////////////////////////////////////////////////////////////////////////////////////
579
// PUBLIC API
580
///////////////////////////////////////////////////////////////////////////////////////////////////
581
/**
582
 * Draws all the attached children to this OutputSurface's 0th FBO.
583
 * <p>
584
 * Must be called from a thread holding OpenGL Context.
585
 *
586
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
587
 * @return Number of objects rendered.
588
 */
589
  public int render(long time)
590
    {
591
    return render(time,0);
592
    }
593

    
594
///////////////////////////////////////////////////////////////////////////////////////////////////
595
/**
596
 * Draws all the attached children to this OutputSurface.
597
 * <p>
598
 * Must be called from a thread holding OpenGL Context.
599
 *
600
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
601
 * @param fbo The surface can have many FBOs backing it up - render this to FBO number 'fbo'.
602
 * @return Number of objects rendered.
603
 */
604
  public int render(long time, int fbo)
605
    {
606
    InternalMaster.toDo();
607
    toDo();
608
    InternalRenderState.reset();
609

    
610
    int numRenders=0, numChildren = mChildren.getNumChildren();
611
    DistortedNode node;
612
    long oldBucket=0, newBucket;
613

    
614
    for(int i=0; i<numChildren; i++)
615
      {
616
      node = mChildren.getChild(i);
617
      newBucket = node.getBucket();
618
      numRenders += node.renderRecursive(time);
619
      if( newBucket<oldBucket ) mChildren.rearrangeByBuckets(i,newBucket);
620
      else oldBucket=newBucket;
621
      }
622

    
623
    numRenders += renderChildren(time,numChildren,mChildren,fbo, mRenderWayOIT);
624

    
625
    return numRenders;
626
    }
627

    
628
///////////////////////////////////////////////////////////////////////////////////////////////////
629
/**
630
 * Bind this Surface as a Framebuffer we can render to.
631
 * <p>
632
 * This version does not attempt to clear anything.
633
 */
634
  public void setAsOutput()
635
    {
636
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
637
    }
638

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

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

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

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

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

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

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

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

    
761
    if( mBuffer!=null )
762
      {
763
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
764
      }
765

    
766
    createProjection();
767
    }
768

    
769
///////////////////////////////////////////////////////////////////////////////////////////////////
770
/**
771
 * Return the vertical field of view angle.
772
 *
773
 * @return Vertival Field of View Angle, in degrees.
774
 */
775
  public float getFOV()
776
    {
777
    return mFOV;
778
    }
779

    
780
///////////////////////////////////////////////////////////////////////////////////////////////////
781
/**
782
 * Resize the underlying Framebuffer.
783
 * <p>
784
 * This method can be safely called mid-render as it doesn't interfere with rendering.
785
 *
786
 * @param width The new width.
787
 * @param height The new height.
788
 */
789
  public void resize(int width, int height)
790
    {
791
    if( mWidth!=width || mHeight!=height )
792
      {
793
      mWidth = mRealWidth = width;
794
      mHeight= mRealHeight= height;
795

    
796
      createProjection();
797

    
798
      if( mColorCreated==CREATED )
799
        {
800
        markForCreation();
801
        recreate();
802
        }
803
      }
804
    }
805

    
806
///////////////////////////////////////////////////////////////////////////////////////////////////
807
/**
808
 * Return true if the Surface contains a DEPTH attachment.
809
 *
810
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
811
 */
812
  public boolean hasDepth()
813
    {
814
    return mDepthStencilCreated==CREATED;
815
    }
816

    
817
///////////////////////////////////////////////////////////////////////////////////////////////////
818
/**
819
 * Return true if the Surface contains a STENCIL attachment.
820
 *
821
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
822
 */
823
  public boolean hasStencil()
824
    {
825
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
826
    }
827

    
828
///////////////////////////////////////////////////////////////////////////////////////////////////
829
/**
830
 * When rendering this Node, should we use the Order Independent Transparency render mode?
831
 * <p>
832
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
833
 * fragments in different ways depending on which fragments get rendered first, or the slower
834
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
835
 *
836
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
837
 */
838
  public void setOrderIndependentTransparency(boolean oit)
839
    {
840
    mRenderWayOIT = oit;
841
    }
842

    
843
///////////////////////////////////////////////////////////////////////////////////////////////////
844
/**
845
 * When rendering this Node, should we use the Order Independent Transparency render mode?
846
 * <p>
847
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
848
 * fragments in different ways depending on which fragments get rendered first, or the slower
849
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
850
 *
851
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
852
 * @param initialSize Initial number of transparent fragments we expect, in screenfuls.
853
 *                    I.e '1.0' means 'the scene we are going to render contains dialog_about 1 screen
854
 *                    worth of transparent fragments'. Valid values: 0.0 &lt; initialSize &lt; 10.0
855
 *                    Even if you get this wrong, the library will detect that there are more
856
 *                    transparent fragments than it has space for and readjust its internal buffers,
857
 *                    but only after a few frames during which one will probably see missing objects.
858
 */
859
public void setOrderIndependentTransparency(boolean oit, float initialSize)
860
  {
861
  mRenderWayOIT = oit;
862

    
863
  if( initialSize>0.0f && initialSize<10.0f )
864
    DistortedLibrary.setSSBOSize(initialSize);
865
  }
866

    
867
///////////////////////////////////////////////////////////////////////////////////////////////////
868
/**
869
 * Adds a new child to the last position in the list of our Surface's children.
870
 * <p>
871
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
872
 * InternalMaster (by calling doWork())
873
 *
874
 * @param node The new Node to add.
875
 */
876
  public void attach(DistortedNode node)
877
    {
878
    mChildren.attach(node);
879
    }
880

    
881
///////////////////////////////////////////////////////////////////////////////////////////////////
882
/**
883
 * Adds a new child to the last position in the list of our Surface's children.
884
 * <p>
885
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
886
 * InternalMaster (by calling doWork())
887
 *
888
 * @param surface InputSurface to initialize our child Node with.
889
 * @param effects DistortedEffects to initialize our child Node with.
890
 * @param mesh MeshBase to initialize our child Node with.
891
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
892
 */
893
  public DistortedNode attach(InternalSurface surface, DistortedEffects effects, MeshBase mesh)
894
    {
895
    return mChildren.attach(surface,effects,mesh);
896
    }
897

    
898
///////////////////////////////////////////////////////////////////////////////////////////////////
899
/**
900
 * Removes the first occurrence of a specified child from the list of children of our Surface.
901
 * <p>
902
 * A bit questionable method as there can be many different Nodes attached as children, some
903
 * of them having the same Effects but - for instance - different Mesh. Use with care.
904
 * <p>
905
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
906
 * InternalMaster (by calling doWork())
907
 *
908
 * @param effects DistortedEffects to remove.
909
 */
910
  public void detach(DistortedEffects effects)
911
    {
912
    mChildren.detach(effects);
913
    }
914

    
915
///////////////////////////////////////////////////////////////////////////////////////////////////
916
/**
917
 * Removes the first occurrence of a specified child from the list of children of our Surface.
918
 * <p>
919
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
920
 * InternalMaster (by calling doWork())
921
 *
922
 * @param node The Node to remove.
923
 */
924
  public void detach(DistortedNode node)
925
    {
926
    mChildren.detach(node);
927
    }
928

    
929
///////////////////////////////////////////////////////////////////////////////////////////////////
930
/**
931
 * Removes all children Nodes.
932
 * <p>
933
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
934
 * InternalMaster (by calling doWork())
935
 */
936
  public void detachAll()
937
    {
938
    mChildren.detachAll();
939
    }
940

    
941
///////////////////////////////////////////////////////////////////////////////////////////////////
942
/**
943
 * Return the width of this Surface.
944
 *
945
 * @return width of the Object, in pixels.
946
 */
947
  public int getWidth()
948
    {
949
    return mWidth;
950
    }
951

    
952
///////////////////////////////////////////////////////////////////////////////////////////////////
953
/**
954
 * Return the height of this Surface.
955
 *
956
 * @return height of the Object, in pixels.
957
 */
958
  public int getHeight()
959
    {
960
    return mHeight;
961
    }
962
}
(12-12/14)