Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 70b6a155

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 org.distorted.library.effect.EffectQuality;
26

    
27
import java.util.ArrayList;
28

    
29
///////////////////////////////////////////////////////////////////////////////////////////////////
30
/**
31
 * This is not really part of the public API.
32
 *
33
 * @y.exclude
34
 */
35
public abstract class DistortedOutputSurface extends DistortedSurface implements DistortedMaster.Slave
36
{
37
//////////// DEBUG FLAGS /////////////////////////////////////////////
38
/**
39
 * When rendering a Screen, show FPS in the upper-left corner?
40
 */
41
public static final int DEBUG_FPS = 1;
42
//////////// END DEBUG FLAGS /////////////////////////////////////////
43

    
44
/**
45
 * Do not create DEPTH or STENCIL attachment
46
 */
47
  public static final int NO_DEPTH_NO_STENCIL = 0;
48
/**
49
 * Create DEPTH, but not STENCIL
50
 */
51
  public static final int DEPTH_NO_STENCIL    = 1;
52
/**
53
 * Create both DEPTH and STENCIL
54
 */
55
  public static final int BOTH_DEPTH_STENCIL  = 2;
56

    
57
  private static final int ATTACH = 0;
58
  private static final int DETACH = 1;
59
  private static final int DETALL = 2;
60
  private static final int SORT   = 3;
61

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

    
65
  private class Job
66
    {
67
    int type;
68
    DistortedNode node;
69

    
70
    Job(int t, DistortedNode n)
71
      {
72
      type = t;
73
      node = n;
74
      }
75
    }
76

    
77
  private ArrayList<Job> mJobs = new ArrayList<>();
78

    
79
  DistortedOutputSurface[] mBuffer;
80

    
81
  private long mTime;
82
  private float mFOV;
83
  float mDistance, mNear;
84
  float[] mProjectionMatrix;
85

    
86
  int mDepthStencilCreated;
87
  int mDepthStencil;
88
  int[] mDepthStencilH = new int[1];
89
  int[] mFBOH          = new int[1];
90

    
91
  private float mClearR, mClearG, mClearB, mClearA;
92
  private float mClearDepth;
93
  private int mClearStencil;
94
  private int mClear;
95
  float mMipmap;
96

    
97
  private int mDebugLevel;
98

    
99
private String sLast="", sCurr="";
100

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

    
103
  abstract void prepareDebug(long time);
104
  abstract void renderDebug(long time);
105

    
106
///////////////////////////////////////////////////////////////////////////////////////////////////
107

    
108
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
109
    {
110
    super(width,height,createColor,numcolors,type);
111

    
112
    mProjectionMatrix = new float[16];
113

    
114
    mFOV = 60.0f;
115
    mNear=  0.5f;
116

    
117
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
118
    mDepthStencil = depthStencil;
119

    
120
    mFBOH[0]         = fbo;
121
    mDepthStencilH[0]= 0;
122

    
123
    mTime = 0;
124
    mDebugLevel = 0;
125

    
126
    mClearR = 0.0f;
127
    mClearG = 0.0f;
128
    mClearB = 0.0f;
129
    mClearA = 0.0f;
130

    
131
    mClearDepth = 1.0f;
132
    mClearStencil = 0;
133
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
134

    
135
    mBuffer = new DistortedOutputSurface[1+EffectQuality.LENGTH];
136

    
137
    mMipmap = 1.0f;
138

    
139
    createProjection();
140
    }
141

    
142
///////////////////////////////////////////////////////////////////////////////////////////////////
143

    
144
  private void createProjection()
145
    {
146
    if( mWidth>0 && mHeight>1 )
147
      {
148
      if( mFOV>0.0f )  // perspective projection
149
        {
150
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
151
        float q = mWidth*mNear;
152
        float c = mHeight*mNear;
153

    
154
        float left   = -q/2;
155
        float right  = +q/2;
156
        float bottom = -c/2;
157
        float top    = +c/2;
158
        float near   =  c/a;
159

    
160
        mDistance    = mHeight/a;
161
        float far    = 2*mDistance-near;
162

    
163
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
164
        }
165
      else             // parallel projection
166
        {
167
        float left   = -mWidth/2.0f;
168
        float right  = +mWidth/2.0f;
169
        float bottom = -mHeight/2.0f;
170
        float top    = +mHeight/2.0f;
171
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
172
        mDistance    = mWidth+mHeight;
173
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
174

    
175
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
176
        }
177
      }
178
    }
179

    
180
///////////////////////////////////////////////////////////////////////////////////////////////////
181

    
182
  private void createBuffers()
183
    {
184
    float mipmap=1.0f;
185

    
186
    for(int j=0; j<EffectQuality.LENGTH; j++)
187
      {
188
      mBuffer[j] = new DistortedFramebuffer(2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
189
      mBuffer[j].mMipmap = mipmap;
190
      mBuffer[j].mNear   = mNear;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
191
      mBuffer[j].glClearColor(1.0f,1.0f,1.0f,0.0f);
192
      mipmap *= EffectQuality.MULTIPLIER;
193
      }
194

    
195
    mBuffer[EffectQuality.LENGTH] = this;
196

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

    
199
    GLES30.glStencilMask(0xff);
200
    GLES30.glDepthMask(true);
201
    GLES30.glColorMask(true,true,true,true);
202
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
203
    GLES30.glClearDepthf(1.0f);
204
    GLES30.glClearStencil(0);
205

    
206
    for(int j=0; j<EffectQuality.LENGTH; j++)
207
      {
208
      mBuffer[j].setAsOutput();
209
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
210
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
211
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
212
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
213
      }
214
    }
215

    
216
///////////////////////////////////////////////////////////////////////////////////////////////////
217

    
218
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer)
219
    {
220
    GLES30.glViewport(0, 0, mWidth, mHeight);
221
    setAsOutput(currTime);
222
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
223
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[0]);
224
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
225
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
226

    
227
    GLES30.glDisable(GLES30.GL_STENCIL_TEST);
228
    GLES30.glStencilMask(0x00);
229

    
230
    DistortedEffects.blitDepthPriv(this);
231
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
232
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
233
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
234
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
235

    
236
    // clear buffers
237
    GLES30.glStencilMask(0xff);
238
    GLES30.glDepthMask(true);
239
    GLES30.glColorMask(true,true,true,true);
240
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
241
    GLES30.glClearDepthf(1.0f);
242
    GLES30.glClearStencil(0);
243

    
244
    buffer.setAsOutput();
245
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[1], 0);
246
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
247
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[0], 0);
248
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
249

    
250
    return 1;
251
    }
252

    
253
///////////////////////////////////////////////////////////////////////////////////////////////////
254
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
255
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
256
// to a whole buffer and merge it.
257

    
258
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
259
    {
260
    int quality=0, internalQuality = 0, numRenders = 0, bucketChange = 0;
261
    DistortedNode child1, child2;
262
    EffectQueuePostprocess lastQueue=null, currQueue;
263
    long lastBucket=0, currBucket;
264

    
265
sCurr = "";
266

    
267
    for(int i=0; i<numChildren; i++)
268
      {
269
      child1 = children.get(i);
270
      currQueue = child1.getPostprocessQueue();
271
      currBucket= currQueue.getID();
272

    
273
sCurr += (" "+currBucket);
274

    
275
      if( currBucket==0 ) numRenders += child1.draw(time,this);
276
      else
277
        {
278
        if( mBuffer[0]==null ) createBuffers();
279

    
280
        if( lastBucket!=currBucket )
281
          {
282
          if( lastBucket!=0 )
283
            {
284
            for(int j=bucketChange; j<i; j++)
285
              {
286
              child2 = children.get(j);
287
              numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],lastQueue);
288
              }
289

    
290
            numRenders += lastQueue.postprocess(this);
291
            numRenders += blitWithDepth(time, mBuffer[quality]);
292
            }
293

    
294
          internalQuality = currQueue.getInternalQuality();
295
          quality         = currQueue.getQuality();
296
          bucketChange    = i;
297
          }
298

    
299
        child1.draw(time,mBuffer[quality]);
300
        //numRenders += currQueue.draw(child1,time,mBuffer);
301

    
302
        if( i==numChildren-1 )
303
          {
304
          for(int j=bucketChange; j<numChildren; j++)
305
            {
306
            child2 = children.get(j);
307
            numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],currQueue);
308
            }
309

    
310
          numRenders += currQueue.postprocess(this);
311
          numRenders += blitWithDepth(time, mBuffer[quality]);
312
          }
313
        }
314

    
315
      lastQueue = currQueue;
316
      lastBucket= currBucket;
317
      }
318

    
319
if( !sLast.equals(sCurr) ) android.util.Log.e("surface", "rendering: "+sCurr);
320
sLast = sCurr;
321

    
322
    return numRenders;
323
    }
324

    
325
///////////////////////////////////////////////////////////////////////////////////////////////////
326

    
327
  ArrayList<DistortedNode> getChildren()
328
    {
329
    return mChildren;
330
    }
331

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

    
348
///////////////////////////////////////////////////////////////////////////////////////////////////
349

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

    
362
    // change tree topology (attach and detach children)
363
/*
364
    boolean changed1 =
365
*/
366
    DistortedMaster.toDo();
367
/*
368
    if( changed1 )
369
      {
370
      for(int i=0; i<mNumChildren; i++)
371
        {
372
        mChildren.get(i).debug(0);
373
        }
374

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

    
396
    int numRenders=0;
397

    
398
    for(int i=0; i<mNumChildren; i++)
399
      {
400
      numRenders += mChildren.get(i).renderRecursive(time);
401
      }
402

    
403
    setAsOutput(time);
404
    numRenders += renderChildren(time,mNumChildren,mChildren);
405

    
406
    if( mDebugLevel != 0 ) renderDebug(time);
407

    
408
    return numRenders;
409
    }
410

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

    
424
    if( mTime!=time )
425
      {
426
      mTime = time;
427
      DistortedRenderState.colorDepthStencilOn();
428
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
429
      GLES30.glClearDepthf(mClearDepth);
430
      GLES30.glClearStencil(mClearStencil);
431
      GLES30.glClear(mClear);
432
      DistortedRenderState.colorDepthStencilRestore();
433
      }
434
    }
435

    
436
///////////////////////////////////////////////////////////////////////////////////////////////////
437
/**
438
 * Bind this Surface as a Framebuffer we can render to.
439
 * <p>
440
 * This version does not attempt to clear anything.
441
 */
442

    
443
  public void setAsOutput()
444
    {
445
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
446
    }
447

    
448
///////////////////////////////////////////////////////////////////////////////////////////////////
449
/**
450
 * Return the Near plane of the Projection included in the Surface.
451
 *
452
 * @return the Near plane.
453
 */
454
  public float getNear()
455
    {
456
    return mNear;
457
    }
458

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

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

    
501
///////////////////////////////////////////////////////////////////////////////////////////////////
502
/**
503
 * Uses glClearDepthf() to set up a value with which to clear
504
 * the Depth buffer of our Surface at the beginning of each frame.
505
 *
506
 * @param d the Depth. Default: 1.0f
507
 */
508
  public void glClearDepthf(float d)
509
    {
510
    mClearDepth = d;
511
    }
512

    
513
///////////////////////////////////////////////////////////////////////////////////////////////////
514
/**
515
 * Uses glClearStencil() to set up a value with which to clear the
516
 * Stencil buffer of our Surface at the beginning of each frame.
517
 *
518
 * @param s the Stencil. Default: 0
519
 */
520
  public void glClearStencil(int s)
521
    {
522
    mClearStencil = s;
523
    }
524

    
525
///////////////////////////////////////////////////////////////////////////////////////////////////
526
/**
527
 * Which buffers to Clear at the beginning of each frame?
528
 * <p>
529
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
530
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
531
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
532
 *
533
 * @param mask bitwise OR of BUFFER_BITs to clear.
534
 */
535
  public void glClear(int mask)
536
    {
537
    mClear = mask;
538
    }
539

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

    
557
    if( near<   1.0f && near> 0.0f )
558
      {
559
      mNear= near;
560
      }
561
    else if( near<=0.0f )
562
      {
563
      mNear = 0.01f;
564
      }
565
    else if( near>=1.0f )
566
      {
567
      mNear=0.99f;
568
      }
569

    
570
    if( mBuffer[0]!=null )
571
      {
572
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
573
      }
574

    
575
    createProjection();
576
    }
577

    
578
///////////////////////////////////////////////////////////////////////////////////////////////////
579
/**
580
 * Resize the underlying Framebuffer.
581
 * <p>
582
 * This method can be safely called mid-render as it doesn't interfere with rendering.
583
 *
584
 * @param width The new width.
585
 * @param height The new height.
586
 */
587
  public void resize(int width, int height)
588
    {
589
    if( mWidth!=width || mHeight!=height )
590
      {
591
      mWidth = width;
592
      mHeight= height;
593

    
594
      createProjection();
595

    
596
      if( mColorCreated==CREATED )
597
        {
598
        markForCreation();
599
        recreate();
600
        }
601
      }
602
    }
603

    
604
///////////////////////////////////////////////////////////////////////////////////////////////////
605
/**
606
 * Return true if the Surface contains a DEPTH attachment.
607
 *
608
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
609
 */
610
  public boolean hasDepth()
611
    {
612
    return mDepthStencilCreated==CREATED;
613
    }
614

    
615
///////////////////////////////////////////////////////////////////////////////////////////////////
616
/**
617
 * Return true if the Surface contains a STENCIL attachment.
618
 *
619
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
620
 */
621
  public boolean hasStencil()
622
    {
623
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
624
    }
625

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

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

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

    
679
    for(int i=0; i<mNumChildren; i++)
680
      {
681
      node = mChildren.get(i);
682

    
683
      if( node.getEffects().getID()==id )
684
        {
685
        detached = true;
686
        mJobs.add(new Job(DETACH,node));
687
        DistortedMaster.newSlave(this);
688
        break;
689
        }
690
      }
691

    
692
    if( !detached )
693
      {
694
      // if we failed to detach any, it still might be the case that
695
      // there's an ATTACH job that we need to cancel.
696
      int num = mJobs.size();
697
      Job job;
698

    
699
      for(int i=0; i<num; i++)
700
        {
701
        job = mJobs.get(i);
702

    
703
        if( job.type==ATTACH && job.node.getEffects()==effects )
704
          {
705
          mJobs.remove(i);
706
          break;
707
          }
708
        }
709
      }
710
    }
711

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

    
727
///////////////////////////////////////////////////////////////////////////////////////////////////
728
/**
729
 * Removes all children Nodes.
730
 * <p>
731
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
732
 * DistortedMaster (by calling doWork())
733
 */
734
  public void detachAll()
735
    {
736
    mJobs.add(new Job(DETALL,null));
737
    DistortedMaster.newSlave(this);
738
    }
739

    
740
///////////////////////////////////////////////////////////////////////////////////////////////////
741
/**
742
 * This is not really part of the public API. Has to be public only because it is a part of the
743
 * DistortedSlave interface, which should really be a class that we extend here instead but
744
 * Java has no multiple inheritance.
745
 *
746
 * @y.exclude
747
 */
748
  public void doWork()
749
    {
750
    int num = mJobs.size();
751
    Job job;
752

    
753
    for(int i=0; i<num; i++)
754
      {
755
      job = mJobs.remove(0);
756

    
757
      switch(job.type)
758
        {
759
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
760
                     job.node.setSurfaceParent(this);
761
                     DistortedMaster.addSorted(mChildren,job.node);
762
                     mNumChildren++;
763
                     break;
764
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
765
                       {
766
                       job.node.setSurfaceParent(null);
767
                       mNumChildren--;
768
                       }
769
                     break;
770
        case DETALL: if( mNumChildren>0 )
771
                       {
772
                       DistortedNode tmp;
773

    
774
                       for(int j=mNumChildren-1; j>=0; j--)
775
                         {
776
                         tmp = mChildren.remove(j);
777
                         tmp.setSurfaceParent(null);
778
                         }
779

    
780
                       mNumChildren = 0;
781
                       }
782
                     break;
783
        case SORT  : mChildren.remove(job.node);
784
                     DistortedMaster.addSorted(mChildren,job.node);
785
                     break;
786
        }
787
      }
788
    }
789
}
(8-8/21)