Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedOutputSurface.java @ 893e008d

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
  private static final int ATTACH = 0;
31
  private static final int DETACH = 1;
32
  private static final int DETALL = 2;
33
  private static final int SORT   = 3;
34

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

    
38
  private class Job
39
    {
40
    int type;
41
    DistortedNode node;
42
    DistortedEffectsPostprocess dep;
43

    
44
    Job(int t, DistortedNode n, DistortedEffectsPostprocess d)
45
      {
46
      type = t;
47
      node = n;
48
      dep  = d;
49
      }
50
    }
51

    
52
  private ArrayList<Job> mJobs = new ArrayList<>();
53

    
54
  DistortedFramebuffer mBuffer1, mBuffer2;
55

    
56
  private long mTime;
57
  private float mFOV;
58
  int mWidth,mHeight,mDepth;
59
  float mDistance, mNear;
60
  float[] mProjectionMatrix;
61

    
62
  int mDepthCreated;
63
  int[] mDepthH = new int[1];
64
  int[] mFBOH   = new int[1];
65

    
66
  private float mClearR, mClearG, mClearB, mClearA;
67
  private float mClearDepth;
68

    
69
//private String sNew="", sOld="";
70

    
71
///////////////////////////////////////////////////////////////////////////////////////////////////
72

    
73
  DistortedOutputSurface(int width, int height, int createColor, int createDepth, int fbo, int type)
74
    {
75
    super(width,height,createColor,type);
76

    
77
    mProjectionMatrix = new float[16];
78

    
79
    mWidth = width;
80
    mHeight= height;
81

    
82
    mFOV = 60.0f;
83
    mNear=  0.5f;
84

    
85
    mDepthCreated= createDepth;
86
    mFBOH[0]     = fbo;
87
    mDepthH[0]   = 0;
88

    
89
    mTime = 0;
90

    
91
    mClearR = 0.0f;
92
    mClearG = 0.0f;
93
    mClearB = 0.0f;
94
    mClearA = 0.0f;
95

    
96
    mClearDepth = 1.0f;
97

    
98
    createProjection();
99
    }
100

    
101
///////////////////////////////////////////////////////////////////////////////////////////////////
102

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

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

    
119
        mDistance    = mHeight/a;
120
        float far    = 2*mDistance-near;
121
        mDepth       = (int)((far-near)/2);
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
        mDepth       = (int)((far-near)/2);
135

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

    
141
///////////////////////////////////////////////////////////////////////////////////////////////////
142
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
143
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
144
// to a whole buffer and merge it.
145

    
146
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
147
    {
148
    int numRenders = 0;
149
    DistortedNode child;
150
    DistortedEffectsPostprocess lastP=null, currP;
151
    long lastB=0, currB;
152

    
153
//sNew = "";
154

    
155
    for(int i=0; i<num; i++)
156
      {
157
      child = children.get(i);
158
      currP = child.getEffectsPostprocess();
159
      currB = currP==null ? 0 : currP.getBucket();
160

    
161
//sNew += currB;
162

    
163
      if( lastB!=currB && lastB!=0 )
164
        {
165
        numRenders += lastP.postprocess(time,this);
166
        }
167

    
168
      if( currB==0 )
169
        {
170
        numRenders += child.draw(time,this);
171
        }
172
      else
173
        {
174
        if( mBuffer1==null )
175
          {
176
          mBuffer1 = new DistortedFramebuffer(mDepthCreated!=DONT_CREATE, DistortedSurface.TYPE_SYST, mWidth, mHeight);
177
          mBuffer2 = new DistortedFramebuffer(false                     , DistortedSurface.TYPE_SYST, mWidth, mHeight);
178
          DistortedSurface.toDo();  // create immediately
179
          }
180

    
181
        numRenders += child.draw(time,mBuffer1);
182
        if( i==num-1 )
183
          {
184
          numRenders += currP.postprocess(time,this);
185
          }
186
        }
187

    
188
      lastP = currP;
189
      lastB = currB;
190
      }
191
/*
192
if( !sNew.equals(sOld) )
193
  {
194
  sOld = sNew;
195
  android.util.Log.e("surface", "Surface"+getID()+": "+sOld);
196
  }
197
*/
198
    return numRenders;
199
    }
200

    
201
///////////////////////////////////////////////////////////////////////////////////////////////////
202

    
203
  void newJob(int t, DistortedNode n, DistortedEffectsPostprocess d)
204
    {
205
    mJobs.add(new Job(t,n,d));
206
    }
207

    
208
///////////////////////////////////////////////////////////////////////////////////////////////////
209
// PUBLIC API
210
///////////////////////////////////////////////////////////////////////////////////////////////////
211
/**
212
 * Draws all the attached children to this OutputSurface.
213
 * <p>
214
 * Must be called from a thread holding OpenGL Context.
215
 *
216
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
217
 * @return Number of objects rendered.
218
 */
219
  public int render(long time)
220
    {
221
    // change tree topology (attach and detach children)
222
/*
223
    boolean changed =
224
*/
225
    DistortedMaster.toDo();
226
/*
227
    // debugging only
228
    if( changed )
229
      {
230
      for(int i=0; i<mNumChildren; i++)
231
        {
232
        mChildren.get(i).debug(0);
233
        }
234

    
235
      DistortedNode.debugMap();
236
      }
237
*/
238
    // create and delete all underlying OpenGL resources
239
    // Watch out: FIRST change topology, only then deal
240
    // with OpenGL resources. That's because changing Tree
241
    // can result in additional Framebuffers that would need
242
    // to be created immediately, before the calls to drawRecursive()
243
    toDo();
244
/*
245
    // debugging only
246
    if( changed )
247
      {
248
      DistortedSurface.debugLists();
249
      }
250
*/
251
    // mark OpenGL state as unknown
252
    DistortedRenderState.reset();
253

    
254
    int numRenders=0;
255

    
256
    for(int i=0; i<mNumChildren; i++)
257
      {
258
      numRenders += mChildren.get(i).renderRecursive(time);
259
      }
260

    
261
    setAsOutput(time);
262
    numRenders += renderChildren(time,mNumChildren,mChildren);
263

    
264
    return numRenders;
265
    }
266

    
267
///////////////////////////////////////////////////////////////////////////////////////////////////
268
/**
269
 * Bind this Surface as a Framebuffer we can render to.
270
 *
271
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
272
 *             out if this is the first time during present frame that this FBO is being set as output.
273
 *             If so, the library, in addition to binding the Surface for output, also clears the
274
 *             Surface's color and depth attachments.
275
 */
276
  public void setAsOutput(long time)
277
    {
278
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
279

    
280
    if( mTime!=time )
281
      {
282
      mTime = time;
283
      DistortedRenderState.colorDepthOn();
284
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
285
      GLES30.glClearDepthf(mClearDepth);
286
      GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
287
      }
288
    }
289

    
290
///////////////////////////////////////////////////////////////////////////////////////////////////
291
/**
292
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
293
 * this Surface before each render.
294
 *
295
 * @param r the Red component. Default: 0.0f
296
 * @param g the Green component. Default: 0.0f
297
 * @param b the Blue component. Default: 0.0f
298
 * @param a the Alpha component. Default: 0.0f
299
 */
300
  public void glClearColor(float r, float g, float b, float a)
301
    {
302
    mClearR = r;
303
    mClearG = g;
304
    mClearB = b;
305
    mClearA = a;
306
    }
307

    
308
///////////////////////////////////////////////////////////////////////////////////////////////////
309
/**
310
 * Set the Depth value of GLES30.glClearDepthf() to set up depth with which to clear
311
 * the Depth buffer of Surface before each render.
312
 *
313
 * @param d the Depth. Default: 1.0f
314
 */
315
  public void glClearDepthf(float d)
316
    {
317
    mClearDepth = d;
318
    }
319

    
320
///////////////////////////////////////////////////////////////////////////////////////////////////
321
/**
322
 * Create new Projection matrix.
323
 *
324
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
325
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
326
 * @param near Distance between the screen plane and the near plane.
327
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
328
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
329
 */
330
  public void setProjection(float fov, float near)
331
    {
332
    if( fov < 180.0f && fov >=0.0f )
333
      {
334
      mFOV = fov;
335
      }
336

    
337
    if( near<   1.0f && near> 0.0f )
338
      {
339
      mNear= near;
340
      }
341
    else if( near<=0.0f )
342
      {
343
      mNear = 0.01f;
344
      }
345
    else if( near>=1.0f )
346
      {
347
      mNear=0.99f;
348
      }
349

    
350
    createProjection();
351
    }
352

    
353
///////////////////////////////////////////////////////////////////////////////////////////////////
354
/**
355
 * Resize the underlying Framebuffer.
356
 * <p>
357
 * This method can be safely called mid-render as it doesn't interfere with rendering.
358
 *
359
 * @param width The new width.
360
 * @param height The new height.
361
 */
362
  public void resize(int width, int height)
363
    {
364
    if( mWidth!=width || mHeight!=height )
365
      {
366
      mWidth = width;
367
      mHeight= height;
368
      mSizeX = width;
369
      mSizeY = height;
370

    
371
      createProjection();
372

    
373
      if( mColorCreated==CREATED )
374
        {
375
        markForCreation();
376
        recreate();
377
        }
378
      }
379
    }
380

    
381
///////////////////////////////////////////////////////////////////////////////////////////////////
382
/**
383
 * Create a new DEPTH buffer and attach it or (param=false) detach an existing DEPTH attachment and recreate it.
384
 *
385
 * @param enable <bold>true</bold> if we want to attach a new DEPTH buffer to the FBO.<br>
386
 *               <bold>false</bold> if we want to detach the DEPTH attachment.
387
 */
388
  public void enableDepth(boolean enable)
389
    {
390
    if( enable && mDepthCreated==DONT_CREATE )
391
      {
392
      mDepthCreated = NOT_CREATED_YET;
393
      markForCreation();
394
      }
395
    if( !enable && mDepthCreated!=DONT_CREATE )
396
      {
397
      mDepthCreated = DONT_CREATE;
398
      markForCreation();
399
      }
400
    }
401

    
402
///////////////////////////////////////////////////////////////////////////////////////////////////
403
/**
404
 * Return true if the Surface contains a DEPTH attachment.
405
 *
406
 * @return <bold>true</bold> if the FBO contains a DEPTH attachment.
407
 */
408
  public boolean hasDepth()
409
    {
410
    return mDepthCreated==CREATED;
411
    }
412

    
413
///////////////////////////////////////////////////////////////////////////////////////////////////
414
/**
415
 * Adds a new child to the last position in the list of our Surface's children.
416
 * <p>
417
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
418
 * DistortedMaster (by calling doWork())
419
 *
420
 * @param node The new Node to add.
421
 */
422
  public void attach(DistortedNode node)
423
    {
424
    mJobs.add(new Job(ATTACH,node,null));
425
    DistortedMaster.newSlave(this);
426
    }
427

    
428
///////////////////////////////////////////////////////////////////////////////////////////////////
429
/**
430
 * Adds a new child to the last position in the list of our Surface's children.
431
 * <p>
432
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
433
 * DistortedMaster (by calling doWork())
434
 *
435
 * @param surface InputSurface to initialize our child Node with.
436
 * @param effects DistortedEffects to initialize our child Node with.
437
 * @param mesh MeshObject to initialize our child Node with.
438
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
439
 */
440
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
441
    {
442
    DistortedNode node = new DistortedNode(surface,effects,mesh);
443
    mJobs.add(new Job(ATTACH,node,null));
444
    DistortedMaster.newSlave(this);
445
    return node;
446
    }
447

    
448
///////////////////////////////////////////////////////////////////////////////////////////////////
449
/**
450
 * Removes the first occurrence of a specified child from the list of children of our Surface.
451
 * <p>
452
 * A bit questionable method as there can be many different Nodes attached as children, some
453
 * of them having the same Effects but - for instance - different Mesh. Use with care.
454
 * <p>
455
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
456
 * DistortedMaster (by calling doWork())
457
 *
458
 * @param effects DistortedEffects to remove.
459
 */
460
  public void detach(DistortedEffects effects)
461
    {
462
    long id = effects.getID();
463
    DistortedNode node;
464
    boolean detached = false;
465

    
466
    for(int i=0; i<mNumChildren; i++)
467
      {
468
      node = mChildren.get(i);
469

    
470
      if( node.getEffects().getID()==id )
471
        {
472
        detached = true;
473
        mJobs.add(new Job(DETACH,node,null));
474
        DistortedMaster.newSlave(this);
475
        break;
476
        }
477
      }
478

    
479
    if( !detached )
480
      {
481
      // if we failed to detach any, it still might be the case that
482
      // there's an ATTACH job that we need to cancel.
483
      int num = mJobs.size();
484
      Job job;
485

    
486
      for(int i=0; i<num; i++)
487
        {
488
        job = mJobs.get(i);
489

    
490
        if( job.type==ATTACH && job.node.getEffects()==effects )
491
          {
492
          mJobs.remove(i);
493
          break;
494
          }
495
        }
496
      }
497
    }
498

    
499
///////////////////////////////////////////////////////////////////////////////////////////////////
500
/**
501
 * Removes the first occurrence of a specified child from the list of children of our Surface.
502
 * <p>
503
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
504
 * DistortedMaster (by calling doWork())
505
 *
506
 * @param node The Node to remove.
507
 */
508
  public void detach(DistortedNode node)
509
    {
510
    mJobs.add(new Job(DETACH,node,null));
511
    DistortedMaster.newSlave(this);
512
    }
513

    
514
///////////////////////////////////////////////////////////////////////////////////////////////////
515
/**
516
 * Removes all children Nodes.
517
 * <p>
518
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
519
 * DistortedMaster (by calling doWork())
520
 */
521
  public void detachAll()
522
    {
523
    mJobs.add(new Job(DETALL,null,null));
524
    DistortedMaster.newSlave(this);
525
    }
526

    
527
///////////////////////////////////////////////////////////////////////////////////////////////////
528
/**
529
 * This is not really part of the public API. Has to be public only because it is a part of the
530
 * DistortedSlave interface, which should really be a class that we extend here instead but
531
 * Java has no multiple inheritance.
532
 *
533
 * @y.exclude
534
 */
535
  public void doWork()
536
    {
537
    int num = mJobs.size();
538
    Job job;
539

    
540
    for(int i=0; i<num; i++)
541
      {
542
      job = mJobs.remove(0);
543

    
544
      switch(job.type)
545
        {
546
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
547
                     job.node.setSurfaceParent(this);
548
                     DistortedMaster.addSorted(mChildren,job.node);
549
                     mNumChildren++;
550
                     break;
551
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
552
                       {
553
                       job.node.setSurfaceParent(null);
554
                       mNumChildren--;
555
                       }
556
                     break;
557
        case DETALL: if( mNumChildren>0 )
558
                       {
559
                       DistortedNode tmp;
560

    
561
                       for(int j=mNumChildren-1; j>=0; j--)
562
                         {
563
                         tmp = mChildren.remove(j);
564
                         tmp.setSurfaceParent(null);
565
                         }
566

    
567
                       mNumChildren = 0;
568
                       }
569
                     break;
570
        case SORT  : job.node.setPost(job.dep);
571
                     mChildren.remove(job.node);
572
                     DistortedMaster.addSorted(mChildren,job.node);
573
                     break;
574
        }
575
      }
576
    }
577
}
(8-8/24)