Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedOutputSurface.java @ 1d6d261e

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.library;
21

    
22
import android.opengl.GLES30;
23
import android.opengl.Matrix;
24
import java.util.ArrayList;
25

    
26
///////////////////////////////////////////////////////////////////////////////////////////////////
27

    
28
abstract class DistortedOutputSurface extends DistortedSurface implements DistortedSlave
29
{
30
/**
31
 * Do not create DEPTH or STENCIL attachment
32
 */
33
  public static final int NO_DEPTH_NO_STENCIL = 0;
34
/**
35
 * Create DEPTH, but not STENCIL
36
 */
37
  public static final int DEPTH_NO_STENCIL    = 1;
38
/**
39
 * Create both DEPTH and STENCIL
40
 */
41
  public static final int BOTH_DEPTH_STENCIL  = 2;
42

    
43
  private static final int ATTACH = 0;
44
  private static final int DETACH = 1;
45
  private static final int DETALL = 2;
46
  private static final int SORT   = 3;
47

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

    
51
  private class Job
52
    {
53
    int type;
54
    DistortedNode node;
55
    DistortedEffectsPostprocess dep;
56

    
57
    Job(int t, DistortedNode n, DistortedEffectsPostprocess d)
58
      {
59
      type = t;
60
      node = n;
61
      dep  = d;
62
      }
63
    }
64

    
65
  private ArrayList<Job> mJobs = new ArrayList<>();
66

    
67
  DistortedFramebuffer[] mBuffer1, mBuffer2;
68

    
69
  private long mTime;
70
  private float mFOV;
71
  float mDistance, mNear;
72
  float[] mProjectionMatrix;
73

    
74
  int mDepthStencilCreated;
75
  int mDepthStencil;
76
  int[] mDepthStencilH = new int[1];
77
  int[] mFBOH          = new int[1];
78

    
79
  private float mClearR, mClearG, mClearB, mClearA;
80
  private float mClearDepth;
81
  private int mClearStencil;
82
  private int mClear;
83
  float mMipmap;
84

    
85
///////////////////////////////////////////////////////////////////////////////////////////////////
86

    
87
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
88
    {
89
    super(width,height,createColor,numcolors,type);
90

    
91
    mProjectionMatrix = new float[16];
92

    
93
    mFOV = 60.0f;
94
    mNear=  0.5f;
95

    
96
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
97
    mDepthStencil = depthStencil;
98

    
99
    mFBOH[0]         = fbo;
100
    mDepthStencilH[0]= 0;
101

    
102
    mTime = 0;
103

    
104
    mClearR = 0.0f;
105
    mClearG = 0.0f;
106
    mClearB = 0.0f;
107
    mClearA = 0.0f;
108

    
109
    mClearDepth = 1.0f;
110
    mClearStencil = 0;
111
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
112

    
113
    mBuffer1 = new DistortedFramebuffer[EffectQuality.LENGTH];
114
    mBuffer2 = new DistortedFramebuffer[EffectQuality.LENGTH];
115

    
116
    mMipmap = 1.0f;
117

    
118
    createProjection();
119
    }
120

    
121
///////////////////////////////////////////////////////////////////////////////////////////////////
122

    
123
  private void createProjection()
124
    {
125
    if( mWidth>0 && mHeight>1 )
126
      {
127
      if( mFOV>0.0f )  // perspective projection
128
        {
129
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
130
        float q = mWidth*mNear;
131
        float c = mHeight*mNear;
132

    
133
        float left   = -q/2;
134
        float right  = +q/2;
135
        float bottom = -c/2;
136
        float top    = +c/2;
137
        float near   =  c/a;
138

    
139
        mDistance    = mHeight/a;
140
        float far    = 2*mDistance-near;
141

    
142
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
143
        }
144
      else             // parallel projection
145
        {
146
        float left   = -mWidth/2.0f;
147
        float right  = +mWidth/2.0f;
148
        float bottom = -mHeight/2.0f;
149
        float top    = +mHeight/2.0f;
150
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
151
        mDistance    = mWidth+mHeight;
152
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
153

    
154
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
155
        }
156
      }
157
    }
158

    
159
///////////////////////////////////////////////////////////////////////////////////////////////////
160

    
161
  void createBuffers()
162
    {
163
    float mipmap=1.0f;
164

    
165
    for(int j=0; j<EffectQuality.LENGTH; j++)
166
      {
167
      mBuffer1[j] = new DistortedFramebuffer(1,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
168
      mBuffer2[j] = new DistortedFramebuffer(1,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
169
      mBuffer1[j].mMipmap = mipmap;
170
      mBuffer2[j].mMipmap = mipmap;
171
      mipmap *= EffectQuality.MULTIPLIER;
172
      }
173

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

    
176
    GLES30.glStencilMask(0xff);
177
    GLES30.glDepthMask(true);
178
    GLES30.glColorMask(true,true,true,true);
179
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
180
    GLES30.glClearDepthf(1.0f);
181
    GLES30.glClearStencil(0);
182

    
183
    for(int j=0; j<EffectQuality.LENGTH; j++)
184
      {
185
      mBuffer1[j].setAsOutput();
186
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
187
      mBuffer2[j].setAsOutput();
188
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
189
      }
190
    }
191

    
192
///////////////////////////////////////////////////////////////////////////////////////////////////
193
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
194
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
195
// to a whole buffer and merge it.
196

    
197
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
198
    {
199
    int numRenders = 0;
200
    DistortedNode child;
201
    DistortedEffectsPostprocess lastP=null, currP;
202
    long lastB=0, currB;
203

    
204
    for(int i=0; i<num; i++)
205
      {
206
      child = children.get(i);
207
      currP = child.getEffectsPostprocess();
208
      currB = currP==null ? 0 : currP.getBucket();
209

    
210
      if( lastB!=currB && lastB!=0 ) numRenders += lastP.postprocess(time,this);
211

    
212
      if( currB==0 ) numRenders += child.draw(time,this);
213
      else
214
        {
215
        if( mBuffer1[0]==null ) createBuffers();
216
        numRenders += child.markStencilAndDraw(time,this,currP);
217
        if( i==num-1 ) numRenders += currP.postprocess(time,this);
218
        }
219

    
220
      lastP = currP;
221
      lastB = currB;
222
      }
223

    
224
    return numRenders;
225
    }
226

    
227
///////////////////////////////////////////////////////////////////////////////////////////////////
228

    
229
  void newJob(int t, DistortedNode n, DistortedEffectsPostprocess d)
230
    {
231
    mJobs.add(new Job(t,n,d));
232
    }
233

    
234
///////////////////////////////////////////////////////////////////////////////////////////////////
235

    
236
  void setAsOutput()
237
    {
238
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
239
    }
240

    
241
///////////////////////////////////////////////////////////////////////////////////////////////////
242
// PUBLIC API
243
///////////////////////////////////////////////////////////////////////////////////////////////////
244
/**
245
 * Draws all the attached children to this OutputSurface.
246
 * <p>
247
 * Must be called from a thread holding OpenGL Context.
248
 *
249
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
250
 * @return Number of objects rendered.
251
 */
252
  public int render(long time)
253
    {
254
    // change tree topology (attach and detach children)
255
/*
256
    boolean changed1 =
257
*/
258
    DistortedMaster.toDo();
259
/*
260
    if( changed1 )
261
      {
262
      for(int i=0; i<mNumChildren; i++)
263
        {
264
        mChildren.get(i).debug(0);
265
        }
266

    
267
      DistortedNode.debugMap();
268
      }
269
*/
270
    // create and delete all underlying OpenGL resources
271
    // Watch out: FIRST change topology, only then deal
272
    // with OpenGL resources. That's because changing Tree
273
    // can result in additional Framebuffers that would need
274
    // to be created immediately, before the calls to drawRecursive()
275
/*
276
    boolean changed2 =
277
*/
278
    toDo();
279
/*
280
    if( changed2 )
281
      {
282
      DistortedObject.debugLists();
283
      }
284
*/
285
    // mark OpenGL state as unknown
286
    DistortedRenderState.reset();
287

    
288
    int numRenders=0;
289

    
290
    for(int i=0; i<mNumChildren; i++)
291
      {
292
      numRenders += mChildren.get(i).renderRecursive(time);
293
      }
294

    
295
    setAsOutput(time);
296
    numRenders += renderChildren(time,mNumChildren,mChildren);
297

    
298
    return numRenders;
299
    }
300

    
301
///////////////////////////////////////////////////////////////////////////////////////////////////
302
/**
303
 * Bind this Surface as a Framebuffer we can render to.
304
 *
305
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
306
 *             out if this is the first time during present frame that this FBO is being set as output.
307
 *             If so, the library, in addition to binding the Surface for output, also clears the
308
 *             Surface's color and depth attachments.
309
 */
310
  public void setAsOutput(long time)
311
    {
312
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
313

    
314
    if( mTime!=time )
315
      {
316
      mTime = time;
317
      DistortedRenderState.colorDepthStencilOn();
318
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
319
      GLES30.glClearDepthf(mClearDepth);
320
      GLES30.glClearStencil(mClearStencil);
321
      GLES30.glClear(mClear);
322
      }
323
    }
324

    
325
///////////////////////////////////////////////////////////////////////////////////////////////////
326
/**
327
 * Set mipmap level.
328
 * <p>
329
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
330
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
331
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
332
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
333
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
334
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
335
 * <p>
336
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
337
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
338
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
339
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
340
 *
341
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
342
 *               does not make any sense (that would result in loss of speed and no gain in quality)
343
 */
344
  public void setMipmap(float mipmap)
345
    {
346
    mMipmap = mipmap;
347
    }
348

    
349
///////////////////////////////////////////////////////////////////////////////////////////////////
350
/**
351
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
352
 * this Surface at the beginning of each frame.
353
 *
354
 * @param r the Red component. Default: 0.0f
355
 * @param g the Green component. Default: 0.0f
356
 * @param b the Blue component. Default: 0.0f
357
 * @param a the Alpha component. Default: 0.0f
358
 */
359
  public void glClearColor(float r, float g, float b, float a)
360
    {
361
    mClearR = r;
362
    mClearG = g;
363
    mClearB = b;
364
    mClearA = a;
365
    }
366

    
367
///////////////////////////////////////////////////////////////////////////////////////////////////
368
/**
369
 * Uses glClearDepthf() to set up a value with which to clear
370
 * the Depth buffer of our Surface at the beginning of each frame.
371
 *
372
 * @param d the Depth. Default: 1.0f
373
 */
374
  public void glClearDepthf(float d)
375
    {
376
    mClearDepth = d;
377
    }
378

    
379
///////////////////////////////////////////////////////////////////////////////////////////////////
380
/**
381
 * Uses glClearStencil() to set up a value with which to clear the
382
 * Stencil buffer of our Surface at the beginning of each frame.
383
 *
384
 * @param s the Stencil. Default: 0
385
 */
386
  public void glClearStencil(int s)
387
    {
388
    mClearStencil = s;
389
    }
390

    
391
///////////////////////////////////////////////////////////////////////////////////////////////////
392
/**
393
 * Which buffers to Clear at the beginning of each frame?
394
 * <p>
395
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
396
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
397
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
398
 *
399
 * @param mask bitwise OR of BUFFER_BITs to clear.
400
 */
401
  public void glClear(int mask)
402
    {
403
    mClear = mask;
404
    }
405

    
406
///////////////////////////////////////////////////////////////////////////////////////////////////
407
/**
408
 * Create new Projection matrix.
409
 *
410
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
411
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
412
 * @param near Distance between the screen plane and the near plane.
413
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
414
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
415
 */
416
  public void setProjection(float fov, float near)
417
    {
418
    if( fov < 180.0f && fov >=0.0f )
419
      {
420
      mFOV = fov;
421
      }
422

    
423
    if( near<   1.0f && near> 0.0f )
424
      {
425
      mNear= near;
426
      }
427
    else if( near<=0.0f )
428
      {
429
      mNear = 0.01f;
430
      }
431
    else if( near>=1.0f )
432
      {
433
      mNear=0.99f;
434
      }
435

    
436
    createProjection();
437
    }
438

    
439
///////////////////////////////////////////////////////////////////////////////////////////////////
440
/**
441
 * Resize the underlying Framebuffer.
442
 * <p>
443
 * This method can be safely called mid-render as it doesn't interfere with rendering.
444
 *
445
 * @param width The new width.
446
 * @param height The new height.
447
 */
448
  public void resize(int width, int height)
449
    {
450
    if( mWidth!=width || mHeight!=height )
451
      {
452
      mWidth = width;
453
      mHeight= height;
454

    
455
      createProjection();
456

    
457
      if( mColorCreated==CREATED )
458
        {
459
        markForCreation();
460
        recreate();
461
        }
462
      }
463
    }
464

    
465
///////////////////////////////////////////////////////////////////////////////////////////////////
466
/**
467
 * Return true if the Surface contains a DEPTH attachment.
468
 *
469
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
470
 */
471
  public boolean hasDepth()
472
    {
473
    return mDepthStencilCreated==CREATED;
474
    }
475

    
476
///////////////////////////////////////////////////////////////////////////////////////////////////
477
/**
478
 * Return true if the Surface contains a STENCIL attachment.
479
 *
480
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
481
 */
482
  public boolean hasStencil()
483
    {
484
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
485
    }
486

    
487
///////////////////////////////////////////////////////////////////////////////////////////////////
488
/**
489
 * Adds a new child to the last position in the list of our Surface's children.
490
 * <p>
491
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
492
 * DistortedMaster (by calling doWork())
493
 *
494
 * @param node The new Node to add.
495
 */
496
  public void attach(DistortedNode node)
497
    {
498
    mJobs.add(new Job(ATTACH,node,null));
499
    DistortedMaster.newSlave(this);
500
    }
501

    
502
///////////////////////////////////////////////////////////////////////////////////////////////////
503
/**
504
 * Adds a new child to the last position in the list of our Surface's children.
505
 * <p>
506
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
507
 * DistortedMaster (by calling doWork())
508
 *
509
 * @param surface InputSurface to initialize our child Node with.
510
 * @param effects DistortedEffects to initialize our child Node with.
511
 * @param mesh MeshObject to initialize our child Node with.
512
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
513
 */
514
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
515
    {
516
    DistortedNode node = new DistortedNode(surface,effects,mesh);
517
    mJobs.add(new Job(ATTACH,node,null));
518
    DistortedMaster.newSlave(this);
519
    return node;
520
    }
521

    
522
///////////////////////////////////////////////////////////////////////////////////////////////////
523
/**
524
 * Removes the first occurrence of a specified child from the list of children of our Surface.
525
 * <p>
526
 * A bit questionable method as there can be many different Nodes attached as children, some
527
 * of them having the same Effects but - for instance - different Mesh. Use with care.
528
 * <p>
529
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
530
 * DistortedMaster (by calling doWork())
531
 *
532
 * @param effects DistortedEffects to remove.
533
 */
534
  public void detach(DistortedEffects effects)
535
    {
536
    long id = effects.getID();
537
    DistortedNode node;
538
    boolean detached = false;
539

    
540
    for(int i=0; i<mNumChildren; i++)
541
      {
542
      node = mChildren.get(i);
543

    
544
      if( node.getEffects().getID()==id )
545
        {
546
        detached = true;
547
        mJobs.add(new Job(DETACH,node,null));
548
        DistortedMaster.newSlave(this);
549
        break;
550
        }
551
      }
552

    
553
    if( !detached )
554
      {
555
      // if we failed to detach any, it still might be the case that
556
      // there's an ATTACH job that we need to cancel.
557
      int num = mJobs.size();
558
      Job job;
559

    
560
      for(int i=0; i<num; i++)
561
        {
562
        job = mJobs.get(i);
563

    
564
        if( job.type==ATTACH && job.node.getEffects()==effects )
565
          {
566
          mJobs.remove(i);
567
          break;
568
          }
569
        }
570
      }
571
    }
572

    
573
///////////////////////////////////////////////////////////////////////////////////////////////////
574
/**
575
 * Removes the first occurrence of a specified child from the list of children of our Surface.
576
 * <p>
577
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
578
 * DistortedMaster (by calling doWork())
579
 *
580
 * @param node The Node to remove.
581
 */
582
  public void detach(DistortedNode node)
583
    {
584
    mJobs.add(new Job(DETACH,node,null));
585
    DistortedMaster.newSlave(this);
586
    }
587

    
588
///////////////////////////////////////////////////////////////////////////////////////////////////
589
/**
590
 * Removes all children Nodes.
591
 * <p>
592
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
593
 * DistortedMaster (by calling doWork())
594
 */
595
  public void detachAll()
596
    {
597
    mJobs.add(new Job(DETALL,null,null));
598
    DistortedMaster.newSlave(this);
599
    }
600

    
601
///////////////////////////////////////////////////////////////////////////////////////////////////
602
/**
603
 * This is not really part of the public API. Has to be public only because it is a part of the
604
 * DistortedSlave interface, which should really be a class that we extend here instead but
605
 * Java has no multiple inheritance.
606
 *
607
 * @y.exclude
608
 */
609
  public void doWork()
610
    {
611
    int num = mJobs.size();
612
    Job job;
613

    
614
    for(int i=0; i<num; i++)
615
      {
616
      job = mJobs.remove(0);
617

    
618
      switch(job.type)
619
        {
620
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
621
                     job.node.setSurfaceParent(this);
622
                     DistortedMaster.addSorted(mChildren,job.node);
623
                     mNumChildren++;
624
                     break;
625
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
626
                       {
627
                       job.node.setSurfaceParent(null);
628
                       mNumChildren--;
629
                       }
630
                     break;
631
        case DETALL: if( mNumChildren>0 )
632
                       {
633
                       DistortedNode tmp;
634

    
635
                       for(int j=mNumChildren-1; j>=0; j--)
636
                         {
637
                         tmp = mChildren.remove(j);
638
                         tmp.setSurfaceParent(null);
639
                         }
640

    
641
                       mNumChildren = 0;
642
                       }
643
                     break;
644
        case SORT  : job.node.setPost(job.dep);
645
                     mChildren.remove(job.node);
646
                     DistortedMaster.addSorted(mChildren,job.node);
647
                     break;
648
        }
649
      }
650
    }
651
}
(9-9/26)