Project

General

Profile

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

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

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.GLES30;
23
import android.opengl.Matrix;
24

    
25
import java.util.ArrayList;
26

    
27
///////////////////////////////////////////////////////////////////////////////////////////////////
28

    
29
abstract class DistortedOutputSurface extends DistortedSurface implements DistortedSlave
30
{
31
//////////// DEBUG FLAGS /////////////////////////////////////////////
32
/**
33
 * When rendering a Screen, show FPS in the upper-left corner?
34
 */
35
public static final int DEBUG_FPS = 1;
36
//////////// END DEBUG FLAGS /////////////////////////////////////////
37

    
38
/**
39
 * Do not create DEPTH or STENCIL attachment
40
 */
41
  public static final int NO_DEPTH_NO_STENCIL = 0;
42
/**
43
 * Create DEPTH, but not STENCIL
44
 */
45
  public static final int DEPTH_NO_STENCIL    = 1;
46
/**
47
 * Create both DEPTH and STENCIL
48
 */
49
  public static final int BOTH_DEPTH_STENCIL  = 2;
50

    
51
  private static final int ATTACH = 0;
52
  private static final int DETACH = 1;
53
  private static final int DETALL = 2;
54
  private static final int SORT   = 3;
55

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

    
59
  private class Job
60
    {
61
    int type;
62
    DistortedNode node;
63

    
64
    Job(int t, DistortedNode n)
65
      {
66
      type = t;
67
      node = n;
68
      }
69
    }
70

    
71
  private ArrayList<Job> mJobs = new ArrayList<>();
72

    
73
  DistortedFramebuffer[] mBuffer;
74

    
75
  private long mTime;
76
  private float mFOV;
77
  float mDistance, mNear;
78
  float[] mProjectionMatrix;
79

    
80
  int mDepthStencilCreated;
81
  int mDepthStencil;
82
  int[] mDepthStencilH = new int[1];
83
  int[] mFBOH          = new int[1];
84

    
85
  private float mClearR, mClearG, mClearB, mClearA;
86
  private float mClearDepth;
87
  private int mClearStencil;
88
  private int mClear;
89
  float mMipmap;
90

    
91
  private int mDebugLevel;
92

    
93
private String sLast="", sCurr="";
94

    
95
///////////////////////////////////////////////////////////////////////////////////////////////////
96

    
97
  abstract void prepareDebug(long time);
98
  abstract void renderDebug(long time);
99

    
100
///////////////////////////////////////////////////////////////////////////////////////////////////
101

    
102
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
103
    {
104
    super(width,height,createColor,numcolors,type);
105

    
106
    mProjectionMatrix = new float[16];
107

    
108
    mFOV = 60.0f;
109
    mNear=  0.5f;
110

    
111
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
112
    mDepthStencil = depthStencil;
113

    
114
    mFBOH[0]         = fbo;
115
    mDepthStencilH[0]= 0;
116

    
117
    mTime = 0;
118
    mDebugLevel = 0;
119

    
120
    mClearR = 0.0f;
121
    mClearG = 0.0f;
122
    mClearB = 0.0f;
123
    mClearA = 0.0f;
124

    
125
    mClearDepth = 1.0f;
126
    mClearStencil = 0;
127
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
128

    
129
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
130

    
131
    mMipmap = 1.0f;
132

    
133
    createProjection();
134
    }
135

    
136
///////////////////////////////////////////////////////////////////////////////////////////////////
137

    
138
  private void createProjection()
139
    {
140
    if( mWidth>0 && mHeight>1 )
141
      {
142
      if( mFOV>0.0f )  // perspective projection
143
        {
144
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
145
        float q = mWidth*mNear;
146
        float c = mHeight*mNear;
147

    
148
        float left   = -q/2;
149
        float right  = +q/2;
150
        float bottom = -c/2;
151
        float top    = +c/2;
152
        float near   =  c/a;
153

    
154
        mDistance    = mHeight/a;
155
        float far    = 2*mDistance-near;
156

    
157
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
158
        }
159
      else             // parallel projection
160
        {
161
        float left   = -mWidth/2.0f;
162
        float right  = +mWidth/2.0f;
163
        float bottom = -mHeight/2.0f;
164
        float top    = +mHeight/2.0f;
165
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
166
        mDistance    = mWidth+mHeight;
167
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
168

    
169
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
170
        }
171
      }
172
    }
173

    
174
///////////////////////////////////////////////////////////////////////////////////////////////////
175

    
176
  private void createBuffers()
177
    {
178
    float mipmap=1.0f;
179

    
180
    for(int j=0; j<EffectQuality.LENGTH; j++)
181
      {
182
      mBuffer[j] = new DistortedFramebuffer(2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
183
      mBuffer[j].mMipmap = mipmap;
184
      mBuffer[j].mNear   = mNear;  // copy mNear as well (for blitting- see PostprocessEffectBlur.apply() )
185
      mipmap *= EffectQuality.MULTIPLIER;
186
      }
187

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

    
190
    GLES30.glStencilMask(0xff);
191
    GLES30.glDepthMask(true);
192
    GLES30.glColorMask(true,true,true,true);
193
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
194
    GLES30.glClearDepthf(1.0f);
195
    GLES30.glClearStencil(0);
196

    
197
    for(int j=0; j<EffectQuality.LENGTH; j++)
198
      {
199
      mBuffer[j].setAsOutput();
200
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
201
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
202
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
203
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
204
      }
205
    }
206

    
207
///////////////////////////////////////////////////////////////////////////////////////////////////
208

    
209
  private int blitWithDepth(int quality, long currTime)
210
    {
211
    DistortedFramebuffer buffer = mBuffer[quality];
212

    
213
    GLES30.glViewport(0, 0, mWidth, mHeight);
214
    setAsOutput(currTime);
215
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
216
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[0]);
217
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
218
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
219

    
220
    GLES30.glDisable(GLES30.GL_STENCIL_TEST);
221
    GLES30.glStencilMask(0x00);
222

    
223
    DistortedEffects.blitDepthPriv(this);
224
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
225
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
226
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
227
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
228

    
229
    // clear buffers
230
    GLES30.glStencilMask(0xff);
231
    GLES30.glDepthMask(true);
232
    GLES30.glColorMask(true,true,true,true);
233
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
234
    GLES30.glClearDepthf(1.0f);
235
    GLES30.glClearStencil(0);
236

    
237
    buffer.setAsOutput();
238
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[1], 0);
239
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
240
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[0], 0);
241
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
242

    
243
    return 1;
244
    }
245

    
246
///////////////////////////////////////////////////////////////////////////////////////////////////
247
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
248
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
249
// to a whole buffer and merge it.
250

    
251
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
252
    {
253
    int numRenders = 0;
254
    DistortedNode child1, child2;
255
    DistortedEffects lastP=null, currP;
256
    long lastB=0, currB;
257
    int bucketChange=0;
258
    int lastQ=0, currQ;
259

    
260
sCurr = "";
261

    
262
    for(int i=0; i<num; i++)
263
      {
264
      child1 = children.get(i);
265
      currP = child1.getEffects();
266
      currB = currP==null ? 0 : currP.getBucket();
267
      currQ = currP==null ? 0 : currP.getQuality();
268

    
269
sCurr += (" "+currB);
270

    
271
      if( currB==0 ) numRenders += child1.draw(time,this);
272
      else
273
        {
274
        if( mBuffer[0]==null ) createBuffers();
275

    
276
        if( lastB!=currB )
277
          {
278
          if( lastB!=0 )
279
            {
280
            for(int j=bucketChange; j<i; j++)
281
              {
282
              child2 = children.get(j);
283
              numRenders += child2.markStencilAndDepth(time,mBuffer[lastQ],lastP);
284
              }
285

    
286
            numRenders += lastP.postprocess(time, this);
287
            numRenders += blitWithDepth(lastQ,time);
288
            }
289

    
290
          bucketChange = i;
291
          }
292

    
293
        numRenders += child1.draw(time,mBuffer[currQ]);
294

    
295
        if( i==num-1 )
296
          {
297
          for(int j=bucketChange; j<num; j++)
298
            {
299
            child2 = children.get(j);
300
            numRenders += child2.markStencilAndDepth(time,mBuffer[currQ],currP);
301
            }
302

    
303
          numRenders += currP.postprocess(time,this);
304
          numRenders += blitWithDepth(currQ,time);
305
          }
306
        }
307

    
308
      lastQ = currQ;
309
      lastP = currP;
310
      lastB = currB;
311
      }
312

    
313
if( !sLast.equals(sCurr) ) android.util.Log.e("surface", "rendering: "+sCurr);
314
sLast = sCurr;
315

    
316
    return numRenders;
317
    }
318

    
319
///////////////////////////////////////////////////////////////////////////////////////////////////
320

    
321
  ArrayList<DistortedNode> getChildren()
322
    {
323
    return mChildren;
324
    }
325

    
326
///////////////////////////////////////////////////////////////////////////////////////////////////
327
// PUBLIC API
328
///////////////////////////////////////////////////////////////////////////////////////////////////
329
/**
330
 * Make the library show various debugging information.
331
 * <p>
332
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
333
 *
334
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
335
 */
336
  public void setDebug(int bitmask)
337
    {
338
    if( this instanceof DistortedScreen )
339
      mDebugLevel = bitmask;
340
    }
341

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343

    
344
/**
345
 * Draws all the attached children to this OutputSurface.
346
 * <p>
347
 * Must be called from a thread holding OpenGL Context.
348
 *
349
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
350
 * @return Number of objects rendered.
351
 */
352
  public int render(long time)
353
    {
354
    if( mDebugLevel!=0 ) prepareDebug(time);
355

    
356
    // change tree topology (attach and detach children)
357
/*
358
    boolean changed1 =
359
*/
360
    DistortedMaster.toDo();
361
/*
362
    if( changed1 )
363
      {
364
      for(int i=0; i<mNumChildren; i++)
365
        {
366
        mChildren.get(i).debug(0);
367
        }
368

    
369
      DistortedNode.debugMap();
370
      }
371
*/
372
    // create and delete all underlying OpenGL resources
373
    // Watch out: FIRST change topology, only then deal
374
    // with OpenGL resources. That's because changing Tree
375
    // can result in additional Framebuffers that would need
376
    // to be created immediately, before the calls to drawRecursive()
377
/*
378
    boolean changed2 =
379
*/
380
    toDo();
381
/*
382
    if( changed2 )
383
      {
384
      DistortedObject.debugLists();
385
      }
386
*/
387
    // mark OpenGL state as unknown
388
    DistortedRenderState.reset();
389

    
390
    int numRenders=0;
391

    
392
    for(int i=0; i<mNumChildren; i++)
393
      {
394
      numRenders += mChildren.get(i).renderRecursive(time);
395
      }
396

    
397
    numRenders += renderChildren(time,mNumChildren,mChildren);
398

    
399
    if( mDebugLevel != 0 ) renderDebug(time);
400

    
401
    return numRenders;
402
    }
403

    
404
///////////////////////////////////////////////////////////////////////////////////////////////////
405
/**
406
 * Bind this Surface as a Framebuffer we can render to.
407
 *
408
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
409
 *             out if this is the first time during present frame that this FBO is being set as output.
410
 *             If so, the library, in addition to binding the Surface for output, also clears the
411
 *             Surface's color and depth attachments.
412
 */
413
  public void setAsOutput(long time)
414
    {
415
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
416

    
417
    if( mTime!=time )
418
      {
419
      mTime = time;
420
      DistortedRenderState.colorDepthStencilOn();
421
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
422
      GLES30.glClearDepthf(mClearDepth);
423
      GLES30.glClearStencil(mClearStencil);
424
      GLES30.glClear(mClear);
425
      }
426
    }
427

    
428
///////////////////////////////////////////////////////////////////////////////////////////////////
429
/**
430
 * Bind this Surface as a Framebuffer we can render to.
431
 * <p>
432
 * This version does not attempt to clear anything.
433
 */
434

    
435
  public void setAsOutput()
436
    {
437
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
438
    }
439

    
440
///////////////////////////////////////////////////////////////////////////////////////////////////
441
/**
442
 * Return the Near plane of the Projection included in the Surface.
443
 *
444
 * @return the Near plane.
445
 */
446
  public float getNear()
447
    {
448
    return mNear;
449
    }
450

    
451
///////////////////////////////////////////////////////////////////////////////////////////////////
452
/**
453
 * Set mipmap level.
454
 * <p>
455
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
456
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
457
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
458
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
459
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
460
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
461
 * <p>
462
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
463
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
464
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
465
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
466
 *
467
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
468
 *               does not make any sense (that would result in loss of speed and no gain in quality)
469
 */
470
  public void setMipmap(float mipmap)
471
    {
472
    mMipmap = mipmap;
473
    }
474

    
475
///////////////////////////////////////////////////////////////////////////////////////////////////
476
/**
477
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
478
 * this Surface at the beginning of each frame.
479
 *
480
 * @param r the Red component. Default: 0.0f
481
 * @param g the Green component. Default: 0.0f
482
 * @param b the Blue component. Default: 0.0f
483
 * @param a the Alpha component. Default: 0.0f
484
 */
485
  public void glClearColor(float r, float g, float b, float a)
486
    {
487
    mClearR = r;
488
    mClearG = g;
489
    mClearB = b;
490
    mClearA = a;
491
    }
492

    
493
///////////////////////////////////////////////////////////////////////////////////////////////////
494
/**
495
 * Uses glClearDepthf() to set up a value with which to clear
496
 * the Depth buffer of our Surface at the beginning of each frame.
497
 *
498
 * @param d the Depth. Default: 1.0f
499
 */
500
  public void glClearDepthf(float d)
501
    {
502
    mClearDepth = d;
503
    }
504

    
505
///////////////////////////////////////////////////////////////////////////////////////////////////
506
/**
507
 * Uses glClearStencil() to set up a value with which to clear the
508
 * Stencil buffer of our Surface at the beginning of each frame.
509
 *
510
 * @param s the Stencil. Default: 0
511
 */
512
  public void glClearStencil(int s)
513
    {
514
    mClearStencil = s;
515
    }
516

    
517
///////////////////////////////////////////////////////////////////////////////////////////////////
518
/**
519
 * Which buffers to Clear at the beginning of each frame?
520
 * <p>
521
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
522
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
523
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
524
 *
525
 * @param mask bitwise OR of BUFFER_BITs to clear.
526
 */
527
  public void glClear(int mask)
528
    {
529
    mClear = mask;
530
    }
531

    
532
///////////////////////////////////////////////////////////////////////////////////////////////////
533
/**
534
 * Create new Projection matrix.
535
 *
536
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
537
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
538
 * @param near Distance between the screen plane and the near plane.
539
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
540
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
541
 */
542
  public void setProjection(float fov, float near)
543
    {
544
    if( fov < 180.0f && fov >=0.0f )
545
      {
546
      mFOV = fov;
547
      }
548

    
549
    if( near<   1.0f && near> 0.0f )
550
      {
551
      mNear= near;
552
      }
553
    else if( near<=0.0f )
554
      {
555
      mNear = 0.01f;
556
      }
557
    else if( near>=1.0f )
558
      {
559
      mNear=0.99f;
560
      }
561

    
562
    if( mBuffer[0]!=null )
563
      {
564
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
565
      }
566

    
567
    createProjection();
568
    }
569

    
570
///////////////////////////////////////////////////////////////////////////////////////////////////
571
/**
572
 * Resize the underlying Framebuffer.
573
 * <p>
574
 * This method can be safely called mid-render as it doesn't interfere with rendering.
575
 *
576
 * @param width The new width.
577
 * @param height The new height.
578
 */
579
  public void resize(int width, int height)
580
    {
581
    if( mWidth!=width || mHeight!=height )
582
      {
583
      mWidth = width;
584
      mHeight= height;
585

    
586
      createProjection();
587

    
588
      if( mColorCreated==CREATED )
589
        {
590
        markForCreation();
591
        recreate();
592
        }
593
      }
594
    }
595

    
596
///////////////////////////////////////////////////////////////////////////////////////////////////
597
/**
598
 * Return true if the Surface contains a DEPTH attachment.
599
 *
600
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
601
 */
602
  public boolean hasDepth()
603
    {
604
    return mDepthStencilCreated==CREATED;
605
    }
606

    
607
///////////////////////////////////////////////////////////////////////////////////////////////////
608
/**
609
 * Return true if the Surface contains a STENCIL attachment.
610
 *
611
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
612
 */
613
  public boolean hasStencil()
614
    {
615
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
616
    }
617

    
618
///////////////////////////////////////////////////////////////////////////////////////////////////
619
/**
620
 * Adds a new child to the last position in the list of our Surface's children.
621
 * <p>
622
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
623
 * DistortedMaster (by calling doWork())
624
 *
625
 * @param node The new Node to add.
626
 */
627
  public void attach(DistortedNode node)
628
    {
629
    mJobs.add(new Job(ATTACH,node));
630
    DistortedMaster.newSlave(this);
631
    }
632

    
633
///////////////////////////////////////////////////////////////////////////////////////////////////
634
/**
635
 * Adds a new child to the last position in the list of our Surface's children.
636
 * <p>
637
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
638
 * DistortedMaster (by calling doWork())
639
 *
640
 * @param surface InputSurface to initialize our child Node with.
641
 * @param effects DistortedEffects to initialize our child Node with.
642
 * @param mesh MeshObject to initialize our child Node with.
643
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
644
 */
645
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
646
    {
647
    DistortedNode node = new DistortedNode(surface,effects,mesh);
648
    mJobs.add(new Job(ATTACH,node));
649
    DistortedMaster.newSlave(this);
650
    return node;
651
    }
652

    
653
///////////////////////////////////////////////////////////////////////////////////////////////////
654
/**
655
 * Removes the first occurrence of a specified child from the list of children of our Surface.
656
 * <p>
657
 * A bit questionable method as there can be many different Nodes attached as children, some
658
 * of them having the same Effects but - for instance - different Mesh. Use with care.
659
 * <p>
660
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
661
 * DistortedMaster (by calling doWork())
662
 *
663
 * @param effects DistortedEffects to remove.
664
 */
665
  public void detach(DistortedEffects effects)
666
    {
667
    long id = effects.getID();
668
    DistortedNode node;
669
    boolean detached = false;
670

    
671
    for(int i=0; i<mNumChildren; i++)
672
      {
673
      node = mChildren.get(i);
674

    
675
      if( node.getEffects().getID()==id )
676
        {
677
        detached = true;
678
        mJobs.add(new Job(DETACH,node));
679
        DistortedMaster.newSlave(this);
680
        break;
681
        }
682
      }
683

    
684
    if( !detached )
685
      {
686
      // if we failed to detach any, it still might be the case that
687
      // there's an ATTACH job that we need to cancel.
688
      int num = mJobs.size();
689
      Job job;
690

    
691
      for(int i=0; i<num; i++)
692
        {
693
        job = mJobs.get(i);
694

    
695
        if( job.type==ATTACH && job.node.getEffects()==effects )
696
          {
697
          mJobs.remove(i);
698
          break;
699
          }
700
        }
701
      }
702
    }
703

    
704
///////////////////////////////////////////////////////////////////////////////////////////////////
705
/**
706
 * Removes the first occurrence of a specified child from the list of children of our Surface.
707
 * <p>
708
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
709
 * DistortedMaster (by calling doWork())
710
 *
711
 * @param node The Node to remove.
712
 */
713
  public void detach(DistortedNode node)
714
    {
715
    mJobs.add(new Job(DETACH,node));
716
    DistortedMaster.newSlave(this);
717
    }
718

    
719
///////////////////////////////////////////////////////////////////////////////////////////////////
720
/**
721
 * Removes all children Nodes.
722
 * <p>
723
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
724
 * DistortedMaster (by calling doWork())
725
 */
726
  public void detachAll()
727
    {
728
    mJobs.add(new Job(DETALL,null));
729
    DistortedMaster.newSlave(this);
730
    }
731

    
732
///////////////////////////////////////////////////////////////////////////////////////////////////
733
/**
734
 * This is not really part of the public API. Has to be public only because it is a part of the
735
 * DistortedSlave interface, which should really be a class that we extend here instead but
736
 * Java has no multiple inheritance.
737
 *
738
 * @y.exclude
739
 */
740
  public void doWork()
741
    {
742
    int num = mJobs.size();
743
    Job job;
744

    
745
    for(int i=0; i<num; i++)
746
      {
747
      job = mJobs.remove(0);
748

    
749
      switch(job.type)
750
        {
751
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
752
                     job.node.setSurfaceParent(this);
753
                     DistortedMaster.addSorted(mChildren,job.node);
754
                     mNumChildren++;
755
                     break;
756
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
757
                       {
758
                       job.node.setSurfaceParent(null);
759
                       mNumChildren--;
760
                       }
761
                     break;
762
        case DETALL: if( mNumChildren>0 )
763
                       {
764
                       DistortedNode tmp;
765

    
766
                       for(int j=mNumChildren-1; j>=0; j--)
767
                         {
768
                         tmp = mChildren.remove(j);
769
                         tmp.setSurfaceParent(null);
770
                         }
771

    
772
                       mNumChildren = 0;
773
                       }
774
                     break;
775
        case SORT  : mChildren.remove(job.node);
776
                     DistortedMaster.addSorted(mChildren,job.node);
777
                     break;
778
        }
779
      }
780
    }
781
}
(8-8/23)