Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedFramebuffer.java @ 05403bba

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

    
25
import java.util.Iterator;
26
import java.util.LinkedList;
27

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

    
48
  private static boolean mListMarked = false;
49
  private static LinkedList<DistortedFramebuffer> mList = new LinkedList<>();
50

    
51
  private int[] texIds = new int[1];
52
  private int[] fboIds = new int[1];
53

    
54
  private boolean mMarked;
55

    
56
  // Projection stuff
57
  private float mX, mY, mFOV;
58
  int mWidth,mHeight,mDepth;
59
  float mDistance;
60
  float[] mProjectionMatrix;
61

    
62
///////////////////////////////////////////////////////////////////////////////////////////////////
63
// Must be called from a thread holding OpenGL Context
64

    
65
  boolean createFBO()
66
    {
67
    if( texIds[0]==TEXTURE_NOT_CREATED_YET )
68
      {
69
      GLES20.glGenTextures(1, texIds, 0);
70
      GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texIds[0]);
71
      GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
72
      GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
73
      GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
74
      GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
75
      GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, mWidth, mHeight, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
76

    
77
      GLES20.glGenFramebuffers(1, fboIds, 0);
78
      GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboIds[0]);
79
      GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, texIds[0], 0);
80

    
81
      int status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER);
82

    
83
      if(status != GLES20.GL_FRAMEBUFFER_COMPLETE)
84
        {
85
        android.util.Log.e("DistortedFramebuffer", "failed to create framebuffer, error="+status);
86
        GLES20.glDeleteTextures(1, texIds, 0);
87
        GLES20.glDeleteFramebuffers(1, fboIds, 0);
88
        fboIds[0] = 0;
89
        texIds[0] = TEXTURE_FAILED_TO_CREATE;
90
        return false;
91
        }
92

    
93
      mList.add(this);
94
      //android.util.Log.e("FBO", "created ("+mWidth+","+mHeight+") "+fboIds[0]);
95
      }
96

    
97
    return true;
98
    }
99

    
100
///////////////////////////////////////////////////////////////////////////////////////////////////
101
// Must be called from a thread holding OpenGL Context
102

    
103
  private void deleteFBO()
104
    {
105
    if( texIds[0]>=0 )
106
      {
107
      //android.util.Log.e("FBO", "deleting ("+mWidth+","+mHeight+") "+fboIds[0]);
108

    
109
      GLES20.glDeleteTextures(1, texIds, 0);
110
      GLES20.glDeleteFramebuffers(1, fboIds, 0);
111

    
112
      fboIds[0] = 0;
113
      texIds[0] = TEXTURE_NOT_CREATED_YET;
114
      }
115

    
116
    mMarked = false;
117
    }
118

    
119
///////////////////////////////////////////////////////////////////////////////////////////////////
120

    
121
  void reset()
122
    {
123
    if( texIds[0]!=TEXTURE_DONT_CREATE)
124
      texIds[0] = TEXTURE_NOT_CREATED_YET;
125
    }
126

    
127
///////////////////////////////////////////////////////////////////////////////////////////////////
128

    
129
  void setAsOutput()
130
    {
131
    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboIds[0]);
132
    }
133

    
134
///////////////////////////////////////////////////////////////////////////////////////////////////
135

    
136
  void setAsInput()
137
    {
138
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texIds[0]);
139
    }
140

    
141
///////////////////////////////////////////////////////////////////////////////////////////////////
142

    
143
  private void createProjection()
144
    {
145
    if( mWidth>0 && mHeight>1 )
146
      {
147
      if( mFOV>0.0f )  // perspective projection
148
        {
149
        float left   = (-mX-mWidth /2.0f)/mHeight;
150
        float right  = (-mX+mWidth /2.0f)/mHeight;
151
        float bottom = (-mY-mHeight/2.0f)/mHeight;
152
        float top    = (-mY+mHeight/2.0f)/mHeight;
153
        float near   = (top-bottom) / (2.0f*(float)Math.tan(mFOV*Math.PI/360));
154
        mDistance    = mHeight*near/(top-bottom);
155
        float far    = 2*mDistance-near;
156
        mDepth       = (int)((far-near)/2);
157

    
158
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
159
        }
160
      else             // parallel projection
161
        {
162
        float left   = -mX-mWidth /2.0f;
163
        float right  = -mX+mWidth /2.0f;
164
        float bottom = -mY-mHeight/2.0f;
165
        float top    = -mY+mHeight/2.0f;
166
        float near   = (mWidth+mHeight)/2;
167
        mDistance    = 2*near;
168
        float far    = 3*near;
169
        mDepth       = (int)near;
170

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

    
176
///////////////////////////////////////////////////////////////////////////////////////////////////
177

    
178
  static synchronized void onDestroy()
179
    {
180
    // There are issues with this. Namely, if one
181
    // 1. creates a DObjectTree (somewhere else than onSurfaceCreated of constructor so it does not get re-created on re-launch)
182
    // 2. exits the app (here mList would be cleared)
183
    // 3. re-launches the app
184
    // 4. deletes some nodes
185
    // then the underlying Framebuffers will never be deleted!
186

    
187
    mListMarked = false;
188
    mList.clear();
189
    }
190

    
191
///////////////////////////////////////////////////////////////////////////////////////////////////
192
// must be called form a thread holding OpenGL Context
193

    
194
  static synchronized void deleteAllMarked()
195
    {
196
    if( mListMarked )
197
      {
198
      DistortedFramebuffer tmp;
199
      Iterator<DistortedFramebuffer> iterator = mList.iterator();
200

    
201
      while(iterator.hasNext())
202
        {
203
        tmp = iterator.next();
204

    
205
        if( tmp.mMarked )
206
          {
207
          tmp.deleteFBO();
208
          iterator.remove();
209
          }
210
        }
211

    
212
      mListMarked = false;
213
      }
214
    }
215

    
216
///////////////////////////////////////////////////////////////////////////////////////////////////
217
// PUBLIC API
218
///////////////////////////////////////////////////////////////////////////////////////////////////
219
/**
220
 * Create a new offscreen Framebuffer.
221
 *
222
 * @param width Width of the COLOR attachment.
223
 * @param height Height of the COLOR attachment.
224
 */
225
  @SuppressWarnings("unused")
226
  public DistortedFramebuffer(int width, int height)
227
    {
228
    mProjectionMatrix = new float[16];
229

    
230
    mHeight  = height;
231
    mWidth   = width;
232
    fboIds[0]= -1;
233
    texIds[0]= TEXTURE_NOT_CREATED_YET;
234
    mFOV     = 60.0f;
235
    mX       = 0.0f;
236
    mY       = 0.0f;
237
    mMarked  = false;
238

    
239
    createProjection();
240
    }
241

    
242
///////////////////////////////////////////////////////////////////////////////////////////////////
243
/**
244
 * Create a new Framebuffer from an already created OpenGL Framebuffer.
245
 * <p>
246
 * Has to be followed by a 'resize()' to set the size.
247
 *
248
 * @param fbo the ID of a OpenGL Framebuffer object. Typically 0 (the screen)
249
 */
250
  public DistortedFramebuffer(int fbo)
251
    {
252
    mProjectionMatrix = new float[16];
253

    
254
    fboIds[0]= fbo;
255
    texIds[0]= TEXTURE_DONT_CREATE;
256
    mFOV     = 60.0f;
257
    mX       = 0.0f;
258
    mY       = 0.0f;
259
    mMarked  = false;
260
    }
261

    
262
///////////////////////////////////////////////////////////////////////////////////////////////////
263
/**
264
 * Draw the (texture,mesh,effects) object to the Framebuffer.
265
 * <p>
266
 * Must be called from a thread holding OpenGL Context.
267
 *
268
 * @param tex input Texture to use.
269
 * @param mesh Class descendant from MeshObject
270
 * @param effects The DistortedEffects to use when rendering
271
 * @param time Current time, in milliseconds.
272
 */
273
  public void renderTo(DistortedTexture tex, MeshObject mesh, DistortedEffects effects, long time)
274
    {
275
    tex.createTexture();
276
    tex.setAsInput();
277
    createFBO();
278
    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboIds[0]);
279
    effects.drawPriv(tex.mHalfX, tex.mHalfY, mesh, this, time);
280
    DistortedFramebuffer.deleteAllMarked();
281
    DistortedTexture.deleteAllMarked();
282
    }
283

    
284
///////////////////////////////////////////////////////////////////////////////////////////////////
285
/**
286
 * Draw the (framebuffer,mesh,effects) object to the Framebuffer.
287
 * <p>
288
 * Must be called from a thread holding OpenGL Context.
289
 *
290
 * @param fbo The Framebuffer (previously created with the first constructor, drawing FROM the screen
291
 *            is unsupported!) whose COLOR attachment 0 will be used as input texture.
292
 *            Please note that rendering from an FBO to itself is unsupported by OpenGL!
293
 * @param mesh Class descendant from MeshObject
294
 * @param effects The DistortedEffects to use when rendering
295
 * @param time Current time, in milliseconds.
296
 */
297
  public void renderTo(DistortedFramebuffer fbo, MeshObject mesh, DistortedEffects effects, long time)
298
    {
299
    fbo.createFBO();
300

    
301
    if( fbo.texIds[0]>0 )    // fbo created with the first constructor
302
      {
303
      createFBO();
304
      GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboIds[0]);
305
      GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, fbo.texIds[0]);
306
      effects.drawPriv(fbo.mWidth/2, fbo.mHeight/2, mesh, this, time);
307
      DistortedFramebuffer.deleteAllMarked();
308
      DistortedTexture.deleteAllMarked();
309
      }
310
    }
311

    
312
///////////////////////////////////////////////////////////////////////////////////////////////////
313
/**
314
 * Draws the Tree, and all its children, to the Framebuffer.
315
 * <p>
316
 * Must be called from a thread holding OpenGL Context.
317
 *
318
 * @param dt DistortedTree to render.
319
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the Tree.
320
 */
321
  public void renderTo(DistortedTree dt, long time)
322
    {
323
    createFBO();
324
    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboIds[0]);
325
    dt.drawRecursive(time,this);
326
    DistortedFramebuffer.deleteAllMarked();
327
    DistortedTexture.deleteAllMarked();
328
    }
329

    
330
///////////////////////////////////////////////////////////////////////////////////////////////////
331
/**
332
 * Mark the underlying OpenGL object for deletion. Actual deletion will take place on the next render.
333
 */
334
  public void markForDeletion()
335
    {
336
    //android.util.Log.e("FBO", "marking for deletion ("+mWidth+","+mHeight+") "+fboIds[0]);
337

    
338
    mListMarked = true;
339
    mMarked     = true;
340
    }
341

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343
/**
344
 * Create new Projection matrix.
345
 *
346
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
347
 * @param x X-coordinate of the point at which our camera looks at. 0 is the center.
348
 * @param y Y-coordinate of the point at which our camera looks at. 0 is the center.
349
 */
350
  public void setProjection(float fov, float x, float y)
351
    {
352
    mFOV = fov;
353
    mX   = x;
354
    mY   = y;
355

    
356
    createProjection();
357
    }
358

    
359
///////////////////////////////////////////////////////////////////////////////////////////////////
360
/**
361
 * Resize the underlying Framebuffer.
362
 *
363
 * As the Framebuffer is not created until the first render, typical usage of this API is actually
364
 * to set the size of an not-yet-created Framebuffer of an object that has been created with the
365
 * second constructor.
366
 * <p>
367
 * Fully creating an object, rendering to it, then resizing mid-render is also possible. Actual
368
 * resize takes place on the next render.
369
 *
370
 * @param width The new width.
371
 * @param height The new height.
372
 */
373
  public void resize(int width, int height)
374
    {
375
    if( mWidth!=width || mHeight!=height )
376
      {
377
      mWidth = width;
378
      mHeight= height;
379

    
380
      createProjection();
381

    
382
      if( texIds[0]>0 ) markForDeletion();
383
      }
384
    }
385

    
386
///////////////////////////////////////////////////////////////////////////////////////////////////
387
/**
388
 * Return the ID of the Texture (COLOR attachment 0) that's backing this FBO.
389
 * <p>
390
 * Catch: this will only work if the library has had time to actually create the texture. Remember
391
 * that the texture gets created only on first render, thus creating a Texture object and immediately
392
 * calling this method will return an invalid (negative) result.
393
 *
394
 * @return If there was not a single render between creation of the Object and calling this method on
395
 *         it, return a negative value. Otherwise, return ID of COLOR attachment 0.
396
 */
397
  public int getTextureID()
398
    {
399
    return texIds[0];
400
    }
401
  }
(3-3/16)