Project

General

Profile

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

library / src / main / java / org / distorted / library / main / EffectQueuePostprocess.java @ fe6fe99a

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

    
25
import org.distorted.library.effect.EffectName;
26
import org.distorted.library.effect.EffectType;
27
import org.distorted.library.effect.PostprocessEffect;
28
import org.distorted.library.R;
29
import org.distorted.library.message.EffectMessage;
30
import org.distorted.library.program.DistortedProgram;
31
import org.distorted.library.program.FragmentCompilationException;
32
import org.distorted.library.program.FragmentUniformsException;
33
import org.distorted.library.program.LinkingException;
34
import org.distorted.library.program.VertexCompilationException;
35
import org.distorted.library.program.VertexUniformsException;
36

    
37
import java.io.InputStream;
38
import java.nio.ByteBuffer;
39
import java.nio.ByteOrder;
40
import java.nio.FloatBuffer;
41

    
42
///////////////////////////////////////////////////////////////////////////////////////////////////
43

    
44
class EffectQueuePostprocess extends EffectQueue
45
  {
46
  private static final int MAX_HALO = 50;    // Support effects creating up to MAX_HALO pixels wide 'halo' around the object.
47

    
48
  private static final int POS_DATA_SIZE= 2; // Post Program: size of the position data in elements
49
  private static final int TEX_DATA_SIZE= 2; // Post Program: size of the texture coordinate data in elements.
50

    
51
  private static final int NUM_UNIFORMS = PostprocessEffect.NUM_UNIFORMS;
52
  private static final int INDEX = EffectType.POSTPROCESS.ordinal();
53

    
54
  private static final FloatBuffer mQuadPositions, mQuadTexture, mQuadTextureInv;
55

    
56
  static
57
    {
58
    int dataLength      = 4;
59
    int bytes_per_float = 4;
60

    
61
    float[] position  = { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
62
    float[] textureNor= {  0.0f,  0.0f,   0.0f, 1.0f,  1.0f, 0.0f,  1.0f, 1.0f };
63
    float[] textureInv= {  0.0f,  0.0f,   1.0f, 0.0f,  0.0f, 1.0f,  1.0f, 1.0f };
64

    
65
    mQuadPositions = ByteBuffer.allocateDirect(POS_DATA_SIZE*dataLength*bytes_per_float).order(ByteOrder.nativeOrder()).asFloatBuffer();
66
    mQuadPositions.put(position).position(0);
67
    mQuadTexture= ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*bytes_per_float).order(ByteOrder.nativeOrder()).asFloatBuffer();
68
    mQuadTexture.put(textureNor).position(0);
69
    mQuadTextureInv= ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*bytes_per_float).order(ByteOrder.nativeOrder()).asFloatBuffer();
70
    mQuadTextureInv.put(textureInv).position(0);
71
    }
72

    
73
  int mQualityLevel;
74
  float mQualityScale;
75
  private int mHalo;
76

    
77
  /////////////////////////////////////////////////////////////////////////////////
78
  // BLUR effect
79
  private static final float GAUSSIAN[] =   // G(0.00), G(0.03), G(0.06), ..., G(3.00), 0
80
    {                                       // where G(x)= (1/(sqrt(2*PI))) * e^(-(x^2)/2). The last 0 terminates.
81
    0.398948f, 0.398769f, 0.398231f, 0.397336f, 0.396086f, 0.394485f, 0.392537f, 0.390247f, 0.387622f, 0.384668f,
82
    0.381393f, 0.377806f, 0.373916f, 0.369733f, 0.365268f, 0.360532f, 0.355538f, 0.350297f, 0.344823f, 0.339129f,
83
    0.333229f, 0.327138f, 0.320868f, 0.314436f, 0.307856f, 0.301142f, 0.294309f, 0.287373f, 0.280348f, 0.273248f,
84
    0.266089f, 0.258884f, 0.251648f, 0.244394f, 0.237135f, 0.229886f, 0.222657f, 0.215461f, 0.208311f, 0.201217f,
85
    0.194189f, 0.187238f, 0.180374f, 0.173605f, 0.166940f, 0.160386f, 0.153951f, 0.147641f, 0.141462f, 0.135420f,
86
    0.129520f, 0.123765f, 0.118159f, 0.112706f, 0.107408f, 0.102266f, 0.097284f, 0.092461f, 0.087797f, 0.083294f,
87
    0.078951f, 0.074767f, 0.070741f, 0.066872f, 0.063158f, 0.059596f, 0.056184f, 0.052920f, 0.049801f, 0.046823f,
88
    0.043984f, 0.041280f, 0.038707f, 0.036262f, 0.033941f, 0.031740f, 0.029655f, 0.027682f, 0.025817f, 0.024056f,
89
    0.022395f, 0.020830f, 0.019357f, 0.017971f, 0.016670f, 0.015450f, 0.014305f, 0.013234f, 0.012232f, 0.011295f,
90
    0.010421f, 0.009606f, 0.008847f, 0.008140f, 0.007483f, 0.006873f, 0.006307f, 0.005782f, 0.005296f, 0.004847f,
91
    0.004432f, 0.000000f
92
    };
93
  private static final int NUM_GAUSSIAN = GAUSSIAN.length-2;
94

    
95
  // The (fixed-function-sampled) Gaussian Blur kernels are of the size k0=1, k1=2, k2=2, k3=3, k4=3, k5=4, k6=4,...
96
  // i.e. k(i)=floor((i+3)/2).  (the 'i' in k(i) means 'blur taking into account the present pixel and 'i' pixels
97
  // in all 4 directions)
98
  // We need room for MAX_BLUR of them, and sum(i=0...N, floor((i+3)/2)) = N + floor(N*N/4)
99
  private static float[] weightsCache = new float[MAX_HALO + MAX_HALO*MAX_HALO/4];
100
  private static float[] offsetsCache = new float[MAX_HALO + MAX_HALO*MAX_HALO/4];
101

    
102
  private static DistortedProgram mBlur1Program, mBlur2Program;
103
  private static int mRadius1H,mOffsets1H,mWeights1H,mDepth1H, mColorTexture1H;
104
  private static int mRadius2H,mOffsets2H,mWeights2H,mDepth2H, mColorTexture2H;
105
  private static float[] mWeights = new float[MAX_HALO];
106
  private static float[] mOffsets = new float[MAX_HALO];
107
  /////////////////////////////////////////////////////////////////////////////////
108
  // GLOW effect
109

    
110

    
111
///////////////////////////////////////////////////////////////////////////////////////////////////
112

    
113
  EffectQueuePostprocess(long id)
114
    { 
115
    super(id,NUM_UNIFORMS,INDEX );
116

    
117
    mQualityLevel = 0;
118
    mQualityScale = 1.0f;
119
    }
120

    
121
///////////////////////////////////////////////////////////////////////////////////////////////////
122

    
123
  static void createProgram(Resources resources)
124
  throws FragmentCompilationException,VertexCompilationException,VertexUniformsException,FragmentUniformsException,LinkingException
125
    {
126
    final InputStream blur1VertexStream   = resources.openRawResource(R.raw.blur_vertex_shader);
127
    final InputStream blur1FragmentStream = resources.openRawResource(R.raw.blur1_fragment_shader);
128

    
129
    try
130
      {
131
      mBlur1Program = new DistortedProgram(blur1VertexStream,blur1FragmentStream,
132
                                          Distorted.GLSL_VERSION,
133
                                          Distorted.GLSL_VERSION + "#define MAX_BLUR "+MAX_HALO, Distorted.GLSL);
134
      }
135
    catch(Exception e)
136
      {
137
      android.util.Log.e("EFFECTS", "exception trying to compile BLUR1 program: "+e.getMessage());
138
      throw new RuntimeException(e.getMessage());
139
      }
140

    
141
    int blur1ProgramH = mBlur1Program.getProgramHandle();
142
    mRadius1H       = GLES30.glGetUniformLocation( blur1ProgramH, "u_Radius");
143
    mOffsets1H      = GLES30.glGetUniformLocation( blur1ProgramH, "u_Offsets");
144
    mWeights1H      = GLES30.glGetUniformLocation( blur1ProgramH, "u_Weights");
145
    mDepth1H        = GLES30.glGetUniformLocation( blur1ProgramH, "u_Depth");
146
    mColorTexture1H = GLES30.glGetUniformLocation( blur1ProgramH, "u_ColorTexture");
147

    
148
    final InputStream blur2VertexStream   = resources.openRawResource(R.raw.blur_vertex_shader);
149
    final InputStream blur2FragmentStream = resources.openRawResource(R.raw.blur2_fragment_shader);
150

    
151
    try
152
      {
153
      mBlur2Program = new DistortedProgram(blur2VertexStream,blur2FragmentStream,
154
                                          Distorted.GLSL_VERSION,
155
                                          Distorted.GLSL_VERSION + "#define MAX_BLUR "+MAX_HALO, Distorted.GLSL);
156
      }
157
    catch(Exception e)
158
      {
159
      android.util.Log.e("EFFECTS", "exception trying to compile BLUR2 program: "+e.getMessage());
160
      // run anyway as compiling Blur2 WILL fail on OpenGL 2.0 contexts
161
      mBlur2Program = mBlur1Program;
162
      }
163

    
164
    int blur2ProgramH = mBlur2Program.getProgramHandle();
165
    mRadius2H       = GLES30.glGetUniformLocation( blur2ProgramH, "u_Radius");
166
    mOffsets2H      = GLES30.glGetUniformLocation( blur2ProgramH, "u_Offsets");
167
    mWeights2H      = GLES30.glGetUniformLocation( blur2ProgramH, "u_Weights");
168
    mDepth2H        = GLES30.glGetUniformLocation( blur2ProgramH, "u_Depth");
169
    mColorTexture2H = GLES30.glGetUniformLocation( blur2ProgramH, "u_ColorTexture");
170
    }
171

    
172
///////////////////////////////////////////////////////////////////////////////////////////////////
173

    
174
  private synchronized void compute(long currTime)
175
    {
176
    if( currTime==mTime ) return;
177
    if( mTime==0 ) mTime = currTime;
178
    long step = (currTime-mTime);
179

    
180
    mHalo = 0;
181
    int halo;
182

    
183
    for(int i=0; i<mNumEffects; i++)
184
      {
185
      mCurrentDuration[i] += step;
186

    
187
      if( mEffects[i].compute(mUniforms, NUM_UNIFORMS*i, mCurrentDuration[i], step) )
188
        {
189
        for(int j=0; j<mNumListeners; j++)
190
          EffectMessageSender.newMessage( mListeners.elementAt(j), EffectMessage.EFFECT_FINISHED, mEffects[i].getID(), mDistortedEffectsID);
191

    
192
        if( mEffects[i].isUnity( mUniforms, NUM_UNIFORMS*i) )
193
          {
194
          remove(i--);
195
          continue;
196
          }
197
        }
198

    
199
      halo = (int)mUniforms[NUM_UNIFORMS*i];
200
      if( halo>mHalo ) mHalo = halo;
201
      }
202

    
203
    mTime = currTime;
204
    }
205

    
206
///////////////////////////////////////////////////////////////////////////////////////////////////
207
// This implements the 'Better separable implementation using GPU fixed function sampling' from
208
// https://software.intel.com/en-us/blogs/2014/07/15/an-investigation-of-fast-real-time-gpu-based-image-blur-algorithms
209

    
210
  private void computeGaussianKernel(int radius)
211
    {
212
    int offset = radius + radius*radius/4;
213

    
214
    if( weightsCache[offset]==0.0f )
215
      {
216
      float z, x= 0.0f, P= (float)NUM_GAUSSIAN / (radius>3 ? radius:3);
217
      mWeights[0] = GAUSSIAN[0];
218
      float sum   = GAUSSIAN[0];
219
      int j;
220

    
221
      for(int i=1; i<=radius; i++)
222
        {
223
        x += P;
224
        j = (int)x;
225
        z = x-j;
226

    
227
        mWeights[i] = (1-z)*GAUSSIAN[j] + z*GAUSSIAN[j+1];
228
        sum += 2*mWeights[i];
229
        }
230

    
231
      for(int i=0; i<=radius; i++) mWeights[i] /= sum;
232

    
233
      int numloops = radius/2;
234
      weightsCache[offset] = mWeights[0];
235
      offsetsCache[offset] = 0.0f;
236

    
237
      for(int i=0; i<numloops; i++)
238
        {
239
        offsetsCache[offset+i+1] = mWeights[2*i+1]*(2*i+1) + mWeights[2*i+2]*(2*i+2);
240
        weightsCache[offset+i+1] = mWeights[2*i+1] + mWeights[2*i+2];
241
        offsetsCache[offset+i+1]/= weightsCache[offset+i+1];
242
        }
243

    
244
      if( radius%2 == 1 )
245
        {
246
        int index = offset + radius/2 +1;
247
        offsetsCache[index]=radius;
248
        weightsCache[index]=mWeights[radius];
249
        }
250
      }
251
    }
252

    
253
///////////////////////////////////////////////////////////////////////////////////////////////////
254

    
255
  long getBucket()
256
    {
257
    return mNumEffects>0 ? mEffects[0].getID() : 0;
258
    }
259

    
260
///////////////////////////////////////////////////////////////////////////////////////////////////
261

    
262
  int getHalo()
263
    {
264
    return mNumEffects>0 ? mHalo : 0;
265
    }
266

    
267
///////////////////////////////////////////////////////////////////////////////////////////////////
268

    
269
  int postprocess(long time, DistortedOutputSurface surface)
270
    {
271
    int numRenders = 0;
272

    
273
    if( mNumEffects>0 )
274
      {
275
      compute(time);
276

    
277
      for(int i=0; i<mNumEffects; i++)
278
        {
279
        if (mName[i] == EffectName.BLUR.ordinal() )
280
          {
281
          blur(NUM_UNIFORMS*i,surface);
282
          numRenders += 2;
283
          }
284
        else if (mName[i] == EffectName.GLOW.ordinal() )
285
          {
286
          glow(NUM_UNIFORMS*i,surface);
287
          numRenders += 2;
288
          }
289
        }
290
      }
291

    
292
    return numRenders;
293
    }
294

    
295
///////////////////////////////////////////////////////////////////////////////////////////////////
296

    
297
  private void blur(int index, DistortedOutputSurface surface)
298
    {
299
    DistortedFramebuffer buffer = surface.mBuffer[mQualityLevel];
300
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, buffer.mFBOH[0]);
301

    
302
    float w1 = buffer.mWidth;
303
    float h1 = buffer.mHeight;
304

    
305
    int radius = (int)(mUniforms[index]*mQualityScale);
306
    if( radius>=MAX_HALO ) radius = MAX_HALO-1;
307
    computeGaussianKernel(radius);
308

    
309
    int offset = radius + radius*radius/4;
310
    radius = (radius+1)/2;
311

    
312
    // horizontal blur
313
    GLES30.glViewport(0, 0, (int)w1, (int)h1);
314
    mBlur1Program.useProgram();
315
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[1], 0);
316
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
317
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[0]);
318

    
319
    GLES30.glUniform1fv( mWeights1H, radius+1, weightsCache,offset);
320
    GLES30.glUniform1i( mRadius1H, radius);
321
    GLES30.glUniform1f( mDepth1H , 1.0f-surface.mNear);
322
    GLES30.glUniform1i( mColorTexture1H , 0 );
323
    for(int i=0; i<=radius; i++) mOffsets[i] = offsetsCache[offset+i]/h1;
324
    GLES30.glUniform1fv( mOffsets1H ,radius+1, mOffsets,0);
325
    GLES30.glVertexAttribPointer(mBlur1Program.mAttribute[0], POS_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadPositions);
326
    GLES30.glVertexAttribPointer(mBlur1Program.mAttribute[1], TEX_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadTexture);
327

    
328
    DistortedRenderState.useStencilMark();
329
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
330
    DistortedRenderState.unuseStencilMark();
331
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
332
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
333

    
334
    // vertical blur
335
    mBlur2Program.useProgram();
336
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[0], 0);
337
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
338
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[1]);
339

    
340
    GLES30.glColorMask(true,true,true,true);
341
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
342
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
343

    
344
    GLES30.glUniform1fv( mWeights2H, radius+1, weightsCache,offset);
345
    GLES30.glUniform1i( mRadius2H, radius);
346
    GLES30.glUniform1f( mDepth2H , 1.0f-surface.mNear);
347
    GLES30.glUniform1i( mColorTexture2H , 0 );
348
    for(int i=0; i<=radius; i++) mOffsets[i] = offsetsCache[offset+i]/w1;
349
    GLES30.glUniform1fv( mOffsets2H ,radius+1, mOffsets,0);
350
    GLES30.glVertexAttribPointer(mBlur2Program.mAttribute[0], POS_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadPositions);
351
    GLES30.glVertexAttribPointer(mBlur2Program.mAttribute[1], TEX_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mQuadTexture);
352

    
353
    DistortedRenderState.useStencilMark();
354
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
355
    DistortedRenderState.unuseStencilMark();
356
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
357
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
358
    }
359

    
360
///////////////////////////////////////////////////////////////////////////////////////////////////
361

    
362
  private void glow(int index, DistortedOutputSurface surface)
363
    {
364

    
365
    }
366
  }
(19-19/23)