Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedFramebuffer.java @ 8ca9f899

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

    
25
///////////////////////////////////////////////////////////////////////////////////////////////////
26
/**
27
 * Class which represents a OpenGL Framebuffer object.
28
 * <p>
29
 * User is able to create either Framebuffers from objects already constructed outside
30
 * of the library (the first constructor; primary use case: the screen) or an offscreen
31
 * FBOs.
32
 * <p>
33
 * Keep all objects created in a static LinkedList. The point: we need to be able to mark
34
 * Framebuffers for deletion, and delete all marked objects later at a convenient time (that's
35
 * because we can only delete from a thread that holds the OpenGL context so here we provide a
36
 * framework where one is able to mark for deletion at any time and actual deletion takes place
37
 * on the next render).
38
 */
39
public class DistortedFramebuffer extends DistortedRenderable
40
  {
41
  private int[] mDepthH = new int[1];
42
  private int[] mFBOH   = new int[1];
43

    
44
  private boolean mDepthEnabled;
45

    
46
  // Projection stuff
47
  private float mX, mY, mFOV;
48
  int mWidth,mHeight,mDepth;
49
  float mDistance;
50
  float[] mProjectionMatrix;
51

    
52
///////////////////////////////////////////////////////////////////////////////////////////////////
53
// Must be called from a thread holding OpenGL Context
54
// Watch out - this has the side-effect of binding a Texture and a Framebuffer!
55

    
56
  void create()
57
    {
58
    if( mColorH[0]==NOT_CREATED_YET )
59
      {
60
      GLES30.glGenTextures(1, mColorH, 0);
61
      GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mColorH[0]);
62
      GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_REPEAT);
63
      GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_REPEAT);
64
      GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST);
65
      GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR);
66
      GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, mSizeX, mSizeY, 0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null);
67

    
68
      GLES30.glGenFramebuffers(1, mFBOH, 0);
69
      GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
70
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mColorH[0], 0);
71

    
72
      checkStatus("color");
73
      }
74
    if( mDepthEnabled && mDepthH[0]==NOT_CREATED_YET ) // we need to create a new DEPTH attachment
75
      {
76
      GLES30.glGenTextures(1, mDepthH, 0);
77
      GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mDepthH[0]);
78
      GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_REPEAT);
79
      GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_REPEAT);
80
      GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST);
81
      GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST);
82
      GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_DEPTH_COMPONENT, mSizeX, mSizeY, 0, GLES30.GL_DEPTH_COMPONENT, GLES30.GL_UNSIGNED_SHORT, null);
83

    
84
      GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
85
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_DEPTH_ATTACHMENT, GLES30.GL_TEXTURE_2D, mDepthH[0], 0);
86

    
87
      checkStatus("depth");
88
      }
89
    if( !mDepthEnabled && mDepthH[0]!=NOT_CREATED_YET ) // we need to detach and destroy the DEPTH attachment.
90
      {
91
      GLES30.glDeleteTextures(1, mDepthH, 0);
92
      mDepthH[0]=NOT_CREATED_YET;
93
      }
94
    }
95

    
96
///////////////////////////////////////////////////////////////////////////////////////////////////
97

    
98
  private boolean checkStatus(String message)
99
    {
100
    int status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER);
101

    
102
    if(status != GLES30.GL_FRAMEBUFFER_COMPLETE)
103
      {
104
      android.util.Log.e("DistortedFramebuffer", "FRAMEBUFFER INCOMPLETE, "+message+" error="+status);
105

    
106
      GLES30.glDeleteTextures(1, mColorH, 0);
107
      GLES30.glDeleteTextures(1, mDepthH, 0);
108
      GLES30.glDeleteFramebuffers(1, mFBOH, 0);
109
      mFBOH[0]   = 0;
110
      mColorH[0] = FAILED_TO_CREATE;
111
      mDepthH[0] = FAILED_TO_CREATE;
112

    
113
      return false;
114
      }
115

    
116
    return true;
117
    }
118

    
119
///////////////////////////////////////////////////////////////////////////////////////////////////
120
// Must be called from a thread holding OpenGL Context
121

    
122
  void delete()
123
    {
124
    if( mColorH[0]>=0 )
125
      {
126
      if( mDepthH[0]>=0 )
127
        {
128
        GLES30.glDeleteTextures(1, mDepthH, 0);
129
        mDepthH[0]=NOT_CREATED_YET;
130
        }
131

    
132
      GLES30.glDeleteTextures(1, mColorH, 0);
133
      mColorH[0] = NOT_CREATED_YET;
134

    
135
      GLES30.glDeleteFramebuffers(1, mFBOH, 0);
136
      mFBOH[0] = 0;
137
      }
138
    }
139

    
140
///////////////////////////////////////////////////////////////////////////////////////////////////
141
// called from onDestroy(); mark OpenGL assets as 'not created'
142

    
143
  void destroy()
144
    {
145
    if( mColorH[0]!=DONT_CREATE ) mColorH[0] = NOT_CREATED_YET;
146
    if( mDepthEnabled           ) mDepthH[0] = NOT_CREATED_YET;
147
    }
148

    
149
///////////////////////////////////////////////////////////////////////////////////////////////////
150

    
151
  void setAsOutput()
152
    {
153
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
154

    
155
    if( mDepthH[0]!=NOT_CREATED_YET )
156
      {
157
      GLES30.glEnable(GLES30.GL_DEPTH_TEST);
158
      GLES30.glDepthMask(true);
159
      }
160
    else
161
      {
162
      GLES30.glDisable(GLES30.GL_DEPTH_TEST);
163
      GLES30.glDepthMask(false);
164
      }
165
    }
166

    
167
///////////////////////////////////////////////////////////////////////////////////////////////////
168

    
169
  private void createProjection()
170
    {
171
    if( mWidth>0 && mHeight>1 )
172
      {
173
      if( mFOV>0.0f )  // perspective projection
174
        {
175
        float left   = (-mX-mWidth /2.0f)/mHeight;
176
        float right  = (-mX+mWidth /2.0f)/mHeight;
177
        float bottom = (-mY-mHeight/2.0f)/mHeight;
178
        float top    = (-mY+mHeight/2.0f)/mHeight;
179
        float near   = (top-bottom) / (2.0f*(float)Math.tan(mFOV*Math.PI/360));
180
        mDistance    = mHeight*near/(top-bottom);
181
        float far    = 2*mDistance-near;
182
        mDepth       = (int)((far-near)/2);
183

    
184
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
185
        }
186
      else             // parallel projection
187
        {
188
        float left   = -mX-mWidth /2.0f;
189
        float right  = -mX+mWidth /2.0f;
190
        float bottom = -mY-mHeight/2.0f;
191
        float top    = -mY+mHeight/2.0f;
192
        float near   = (mWidth+mHeight)/2;
193
        mDistance    = 2*near;
194
        float far    = 3*near;
195
        mDepth       = (int)near;
196

    
197
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
198
        }
199
      }
200
    }
201

    
202
///////////////////////////////////////////////////////////////////////////////////////////////////
203
// if new size fits into the size of the underlying Texture, just change the projection without
204
// reallocating the Texture. Otherwise, we need to reallocate.
205
//
206
// Must be called form a thread holding the OpenGL context.
207

    
208
  void resizeFast(int width, int height)
209
    {
210
    if( mWidth!=width || mHeight!=height )
211
      {
212
      mWidth = width;
213
      mHeight= height;
214

    
215
      createProjection();
216

    
217
      if( mWidth> mSizeX || mHeight> mSizeY)
218
        {
219
        mSizeX = mWidth;
220
        mSizeY = mHeight;
221
        delete();
222
        }
223
      }
224

    
225
    create();
226
    }
227

    
228
///////////////////////////////////////////////////////////////////////////////////////////////////
229
// PUBLIC API
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231
/**
232
 * Create a new offscreen Framebuffer.
233
 *
234
 * @param width Width of the COLOR attachment.
235
 * @param height Height of the COLOR attachment.
236
 * @param depthEnabled Add DEPTH attachment?
237
 */
238
  @SuppressWarnings("unused")
239
  public DistortedFramebuffer(int width, int height, boolean depthEnabled)
240
    {
241
    super(width,height,NOT_CREATED_YET);
242

    
243
    mProjectionMatrix = new float[16];
244

    
245
    mHeight      = height;
246
    mWidth       = width;
247
    mFOV         = 60.0f;
248
    mX           = 0.0f;
249
    mY           = 0.0f;
250
    mDepthEnabled= depthEnabled;
251
    mFBOH[0]     = NOT_CREATED_YET;
252
    mDepthH[0]   = NOT_CREATED_YET;
253

    
254
    createProjection();
255
    }
256

    
257
///////////////////////////////////////////////////////////////////////////////////////////////////
258

    
259
/**
260
 * Create a new offscreen Framebuffer.
261
 *
262
 * @param width Width of the COLOR attachment.
263
 * @param height Height of the COLOR attachment.
264
 */
265
  @SuppressWarnings("unused")
266
  public DistortedFramebuffer(int width, int height)
267
    {
268
    super(width,height,NOT_CREATED_YET);
269

    
270
    mProjectionMatrix = new float[16];
271

    
272
    mHeight      = height;
273
    mWidth       = width;
274
    mFOV         = 60.0f;
275
    mX           = 0.0f;
276
    mY           = 0.0f;
277
    mDepthEnabled= false;
278
    mFBOH[0]     = NOT_CREATED_YET;
279
    mDepthH[0]   = NOT_CREATED_YET;
280

    
281
    createProjection();
282
    }
283

    
284
///////////////////////////////////////////////////////////////////////////////////////////////////
285
/**
286
 * Create a new Framebuffer from an already created OpenGL Framebuffer.
287
 * <p>
288
 * Has to be followed by a 'resize()' to set the size.
289
 *
290
 * @param fbo the ID of a OpenGL Framebuffer object. Typically 0 (the screen)
291
 */
292
  public DistortedFramebuffer(int fbo)
293
    {
294
    super(0,0,DONT_CREATE);
295

    
296
    mProjectionMatrix = new float[16];
297

    
298
    mFOV         = 60.0f;
299
    mX           = 0.0f;
300
    mY           = 0.0f;
301
    mDepthEnabled= true;
302
    mFBOH[0]     = fbo;
303
    mDepthH[0]   = DONT_CREATE;
304
    }
305

    
306
///////////////////////////////////////////////////////////////////////////////////////////////////
307
/**
308
 * Create a new DEPTH buffer and attach it or (param=false) detach an existing DEPTh attachment and destroy it.
309
 *
310
 * @param enable <bold>true</bold> if we want to attach a new DEPTH buffer to the FBO.<br>
311
 *               <bold>false</bold> if we want to detach the DEPTH attachment.
312
 */
313
  public void enableDepthAttachment(boolean enable)
314
    {
315
    mDepthEnabled = enable;
316
    }
317

    
318
///////////////////////////////////////////////////////////////////////////////////////////////////
319

    
320
/**
321
 * Draw the (texture,mesh,effects) object to the Framebuffer.
322
 * <p>
323
 * Must be called from a thread holding OpenGL Context.
324
 *
325
 * @param ren input Renderable to use.
326
 * @param mesh Class descendant from MeshObject
327
 * @param effects The DistortedEffects to use when rendering
328
 * @param time Current time, in milliseconds.
329
 */
330
  public void renderTo(DistortedRenderable ren, MeshObject mesh, DistortedEffects effects, long time)
331
    {
332
    ren.create();  // Watch out  - this needs to be before
333
    create();      // the 'setAsInput' because this has side-effects!
334

    
335
    if( ren.setAsInput() )
336
      {
337
      DistortedRenderable.deleteAllMarked();
338
      effects.drawPriv(ren.getWidth()/2.0f, ren.getHeight()/2.0f, mesh, this, time);
339
      }
340
    }
341

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343
/**
344
 * Draws the Tree, and all its children, to the Framebuffer.
345
 * <p>
346
 * Must be called from a thread holding OpenGL Context.
347
 *
348
 * @param dt DistortedTree to render.
349
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the Tree.
350
 */
351
  public void renderTo(DistortedTree dt, long time)
352
    {
353
    DistortedRenderable.deleteAllMarked();
354
    create();
355
    dt.drawRecursive(time,this);
356
    }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359
/**
360
 * Create new Projection matrix.
361
 *
362
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
363
 * @param x X-coordinate of the point at which our camera looks at. 0 is the center.
364
 * @param y Y-coordinate of the point at which our camera looks at. 0 is the center.
365
 */
366
  public void setProjection(float fov, float x, float y)
367
    {
368
    mFOV = fov;
369
    mX   = x;
370
    mY   = y;
371

    
372
    createProjection();
373
    }
374

    
375
///////////////////////////////////////////////////////////////////////////////////////////////////
376
/**
377
 * Resize the underlying Framebuffer.
378
 *
379
 * As the Framebuffer is not created until the first render, typical usage of this API is actually
380
 * to set the size of an not-yet-created Framebuffer of an object that has been created with the
381
 * second constructor.
382
 * <p>
383
 * Fully creating an object, rendering to it, then resizing mid-render is also possible. Actual
384
 * resize takes place on the next render.
385
 *
386
 * @param width The new width.
387
 * @param height The new height.
388
 */
389
  public void resize(int width, int height)
390
    {
391
    if( mWidth!=width || mHeight!=height )
392
      {
393
      mWidth = width;
394
      mHeight= height;
395
      mSizeX = width;
396
      mSizeY = height;
397

    
398
      createProjection();
399

    
400
      if( mColorH[0]>0 ) markForDeletion();
401
      }
402
    }
403

    
404
///////////////////////////////////////////////////////////////////////////////////////////////////
405
/**
406
 * Return the ID of the Texture (COLOR attachment 0) that's backing this FBO.
407
 * <p>
408
 * Catch: this will only work if the library has had time to actually create the texture. Remember
409
 * that the texture gets created only on first render, thus creating a Texture object and immediately
410
 * calling this method will return an invalid (negative) result.
411
 *
412
 * @return If there was not a single render between creation of the Object and calling this method on
413
 *         it, return a negative value. Otherwise, return ID of COLOR attachment 0.
414
 */
415
  public int getTextureID()
416
    {
417
    return mColorH[0];
418
    }
419

    
420
///////////////////////////////////////////////////////////////////////////////////////////////////
421
/**
422
 * Return true if the FBO contains a DEPTH attachment.
423
 *
424
 * @return <bold>true</bold> if the FBO contains a DEPTH attachment.
425
 */
426
  public boolean hasDepth()
427
    {
428
    return mDepthEnabled;
429
    }
430
  }
(3-3/17)