Project

General

Profile

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

library / src / main / java / org / distorted / library / effect / PostprocessEffect.java @ c226920c

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2017 Leszek Koltunski  leszek@koltunski.pl                                          //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// This library is free software; you can redistribute it and/or                                 //
7
// modify it under the terms of the GNU Lesser General Public                                    //
8
// License as published by the Free Software Foundation; either                                  //
9
// version 2.1 of the License, or (at your option) any later version.                            //
10
//                                                                                               //
11
// This library 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 GNU                             //
14
// Lesser General Public License for more details.                                               //
15
//                                                                                               //
16
// You should have received a copy of the GNU Lesser General Public                              //
17
// License along with this library; if not, write to the Free Software                           //
18
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA                //
19
///////////////////////////////////////////////////////////////////////////////////////////////////
20

    
21
package org.distorted.library.effect;
22

    
23
import org.distorted.library.effectqueue.EffectQueue;
24
import org.distorted.library.main.DistortedFramebuffer;
25
import org.distorted.library.main.InternalMaster;
26
import org.distorted.library.program.DistortedProgram;
27

    
28
import java.lang.reflect.Method;
29
import java.nio.ByteBuffer;
30
import java.nio.ByteOrder;
31
import java.nio.FloatBuffer;
32
import java.util.ArrayList;
33

    
34
///////////////////////////////////////////////////////////////////////////////////////////////////
35
/**
36
 * Abstract class that represents an Effect that works by running a certain Shader Program(s) on a Framebuffer.
37
 */
38
public abstract class PostprocessEffect extends Effect implements InternalMaster.Slave
39
  {
40
  private static final int MIPMAP = 0;
41
  /**
42
   * 5 per-effect interpolated values.
43
   */
44
  public static final int NUM_FLOAT_UNIFORMS = 6;
45
  /**
46
   * 1: the name of the effect
47
   */
48
  public static final int NUM_INT_UNIFORMS = 1;
49

    
50
  static final int POS_DATA_SIZE= 2;
51
  static final int TEX_DATA_SIZE= 2;
52

    
53
  static final FloatBuffer mQuadPositions, mQuadTexture, mQuadTextureInv;
54

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

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

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

    
72
  private static class Source
73
    {
74
    private final String mName, mVertexShader, mFragmentShader;
75

    
76
    Source(String name, String vertex, String fragment)
77
      {
78
      mName           = name;
79
      mVertexShader   = vertex;
80
      mFragmentShader = fragment;
81
      }
82
    }
83

    
84
  static ArrayList<DistortedProgram> mPrograms = new ArrayList<>();
85
  private final static ArrayList<Source> mSources = new ArrayList<>();
86
  private static int mNumSources = 0;
87

    
88
  private static class Job
89
    {
90
    int type;
91
    int level;
92

    
93
    Job(int t, int l)
94
      {
95
      type = t;
96
      level= l;
97
      }
98
    }
99

    
100
  private final ArrayList<Job> mJobs = new ArrayList<>();
101
  private int mQualityLevel;
102
  private boolean mUseHaloDepth;
103

    
104
  float mQualityScale;
105

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

    
108
  static int register(final String name, final String vertexShader, final String fragmentShader)
109
    {
110
    mSources.add(new Source(name,vertexShader,fragmentShader));
111

    
112
    return mNumSources++;
113
    }
114

    
115
///////////////////////////////////////////////////////////////////////////////////////////////////
116
/**
117
 * Only for use by the library itself.
118
 *
119
 * @y.exclude
120
 */
121
  public static void createPrograms(int GLSL)
122
    {
123
    Source source;
124
    int len = mSources.size();
125

    
126
    String version = "#version "+GLSL+" es\n";
127

    
128
    for(int i=0; i<len; i++)
129
      {
130
      source = mSources.remove(0);
131

    
132
      try
133
        {
134
        mPrograms.add (new DistortedProgram(version+source.mVertexShader,version+source.mFragmentShader));
135
        }
136
      catch(Exception e)
137
        {
138
        android.util.Log.e("Effects", "exception trying to compile "+source.mName+" program: "+e.getMessage());
139
        throw new RuntimeException(e.getMessage());
140
        }
141
      }
142
    }
143

    
144
///////////////////////////////////////////////////////////////////////////////////////////////////
145
/**
146
 * At this moment the 'buffer' contains a) preprocessed object b) real object rendered 'on top' of
147
 * the preprocessed one.
148
 * Postprocess buffer. What this means exactly depends on the effect -
149
 *
150
 * Only for use by the library itself.
151
 *
152
 * @y.exclude
153
 */
154
  public abstract int postprocess(float[] uniforms, int index, DistortedFramebuffer buffer);
155

    
156
///////////////////////////////////////////////////////////////////////////////////////////////////
157
  /**
158
   * Do we render the object directly to the final surface, and only postprocess and then blit its
159
   * 'halo', or do we render the object along with its halo to the intermediate framebuffer and
160
   * postprocess it as well?
161
   *
162
   * Only for use by the library itself.
163
   *
164
   * @y.exclude
165
   */
166
  public abstract boolean getRenderDirectly();
167

    
168
///////////////////////////////////////////////////////////////////////////////////////////////////
169
  /**
170
   * Only for use by the library itself.
171
   *
172
   * @y.exclude
173
   */
174
  public int getQuality()
175
    {
176
    return mQualityLevel;
177
    }
178

    
179
///////////////////////////////////////////////////////////////////////////////////////////////////
180
  /**
181
   * Only for use by the library itself.
182
   *
183
   * @y.exclude
184
   */
185
  public boolean getHaloDepth()
186
    {
187
    return mUseHaloDepth;
188
    }
189

    
190
///////////////////////////////////////////////////////////////////////////////////////////////////
191
/**
192
 * Only for use by the library itself.
193
 *
194
 * @y.exclude
195
 */
196
  public void addQueue(EffectQueue queue)
197
    {
198
    // NO OP
199
    }
200

    
201
///////////////////////////////////////////////////////////////////////////////////////////////////
202
/**
203
 * Only for use by the library itself.
204
 *
205
 * @y.exclude
206
 */
207
  public void remQueue(EffectQueue queue)
208
    {
209
    // NO OP
210
    }
211

    
212
///////////////////////////////////////////////////////////////////////////////////////////////////
213
/**
214
 * This is not really part of the public API. Has to be public only because it is a part of the
215
 * DistortedSlave interface, which should really be a class that we extend here instead but
216
 * Java has no multiple inheritance.
217
 *
218
 * @y.exclude
219
 */
220
  public void doWork()
221
    {
222
    int num = mJobs.size();
223
    Job job;
224

    
225
    for(int i=0; i<num; i++)
226
      {
227
      job = mJobs.remove(0);
228

    
229
      switch(job.type)
230
        {
231
        case MIPMAP: int level = job.level;
232
                     mQualityLevel = level;
233
                     mQualityScale = 1.0f;
234
                     for(int j=0; j<level; j++) mQualityScale*= EffectQuality.MULTIPLIER;
235
                     break;
236
        }
237
      }
238
    }
239

    
240
///////////////////////////////////////////////////////////////////////////////////////////////////
241

    
242
  static void destroyStatics()
243
    {
244
    mPrograms.clear();
245
    mSources.clear();
246
    mNumSources = 0;
247

    
248
    Method method;
249

    
250
    for(EffectName name: EffectName.values())
251
      {
252
      if( name.getType() == EffectType.POSTPROCESS )
253
        {
254
        Class<? extends Effect> cls = name.getEffectClass();
255

    
256
        try
257
          {
258
          method = cls.getDeclaredMethod("destroyStatics");  // destroyStatics not public, thus getDeclaredMethod
259
          }
260
        catch(NoSuchMethodException ex)
261
          {
262
          android.util.Log.e("postprocess", cls.getSimpleName()+": exception getting method: "+ex.getMessage());
263
          method = null;
264
          }
265

    
266
        try
267
          {
268
          if( method!=null ) method.invoke(null);
269
          }
270
        catch(Exception ex)
271
          {
272
          android.util.Log.e("postprocess", "exception invoking method: "+ex.getMessage());
273
          }
274
        }
275
      }
276
    }
277

    
278
///////////////////////////////////////////////////////////////////////////////////////////////////
279

    
280
  PostprocessEffect(EffectName name)
281
    {
282
    super(name);
283

    
284
    mQualityLevel = 0;
285
    mQualityScale = 1.0f;
286
    mUseHaloDepth = true;
287
    }
288

    
289
///////////////////////////////////////////////////////////////////////////////////////////////////
290
// PUBLIC API
291
///////////////////////////////////////////////////////////////////////////////////////////////////
292
/**
293
 * The higher the quality, the better the effect will look like and the slower it will be.
294
 * <p>
295
 * This works by rendering into smaller and smaller intermediate buffers. Each step renders into a
296
 * buffer that's half the size of the previous one.
297
 * <p>
298
 * We cannot this during mid-render - thus, give it to the Master to assign us back this job on the
299
 * next render.
300
 */
301
  public void setQuality(EffectQuality quality)
302
    {
303
    mJobs.add(new Job(MIPMAP,quality.getLevel()));
304
    InternalMaster.newSlave(this);
305
    }
306

    
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308
/**
309
 * When preprocessing - so drawning the 'halo' - do we also want to write the depth buffer?
310
 * If yes, the halo would cover the whole object; if no, it would be just around it (and possibly
311
 * could be covered by other similarly postprocessed objects nearby)
312
 *
313
 * @param depth should the halo around the object cover it or not?
314
 */
315
  public void setHaloDepth(boolean depth)
316
    {
317
    mUseHaloDepth = depth;
318
    }
319
  }
(17-17/34)