Statistics
| Revision:

gvsig-raster / org.gvsig.raster / branches / org.gvsig.raster_dataaccess_refactoring / org.gvsig.raster.lib / org.gvsig.raster.lib.api / src / main / java / org / gvsig / fmap / dal / coverage / grid / filter / BaseRasterFilter.java @ 2348

History | View | Annotate | Download (13.7 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program 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 this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.fmap.dal.coverage.grid.filter;
23

    
24
import java.util.Hashtable;
25
import java.util.TreeMap;
26

    
27
import org.gvsig.fmap.dal.coverage.RasterLocator;
28
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
29
import org.gvsig.fmap.dal.coverage.dataset.BufferParam;
30
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
31
import org.gvsig.fmap.dal.coverage.datastruct.Params;
32
import org.gvsig.fmap.dal.coverage.exception.BufferCreationException;
33
import org.gvsig.fmap.dal.coverage.exception.FilterAddException;
34
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
35
import org.gvsig.fmap.dal.coverage.grid.RasterFilter;
36
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
37
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
38
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
39
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
40
import org.gvsig.tools.locator.LocatorException;
41

    
42
/**
43
 * Base class for all filters
44
 *
45
 * @author Nacho Brodin (nachobrodin@gmail.com)
46
 */
47
public abstract class BaseRasterFilter implements RasterFilter, Cloneable {
48
        public static final String PERSISTENT_NAME        = "BaseRasterFilter";
49
    public static final String PERSISTENT_DESCRIPTION = "BaseRasterFilter Persistent";
50
        protected Buffer           raster                 = null;
51
        protected Buffer           rasterResult           = null;
52
        protected int              height                 = 0;
53
        protected int              width                  = 0;
54
        protected Hashtable<String, Object> 
55
                                   params                 = new Hashtable<String, Object>();
56
        protected TreeMap<String, Object>   
57
                                   environment            = new TreeMap<String, Object>();
58
        protected Extent           extent                 = null;
59
        private int                percent                = 0;
60
        private String             fName                  = "";
61
        /**
62
         * Variable que control la aplicaci?n o no del filtro. Si est? a false aunque est? en
63
         * la pila el filtro no se ejecutar?.
64
         */
65
        protected boolean           exec                  = true;
66
        protected RasterUtils       util                  = null;
67
        protected TaskEventManager  taskEventManager      = null;
68
        protected String            managername           = null;
69
        protected Transparency      transparency          = null;
70
        
71
        private boolean             hasInputTransparency       = false;
72
        protected int               nBandsToProcess       = 0;
73
        protected ColorInterpretation 
74
                                    colorInterpretation   = null;
75
        private boolean             argbOutput            = false;
76

    
77
        /**
78
         * Constructor
79
         */
80
        public BaseRasterFilter() {
81
                if(RasterLocator.getManager() != null)
82
                        util = RasterLocator.getManager().getRasterUtils();
83
        }
84

    
85
        /**
86
         * Aplica el filtro sobre el raster pasado pixel a pixel
87
         * @throws ProcessInterruptedException
88
         * @throws FilterAddException 
89
         */
90
        public void execute() throws ProcessInterruptedException, FilterAddException {
91
                taskEventManager = RasterLocator.getManager().createRasterTask(this);
92
                pre();
93
                if (raster != null && raster.getDataType() != this.getInRasterDataType())
94
                        exec = false;
95
                percent = 0;
96
                if (exec)
97
                        for (int row = 0; row < height; row ++) {
98
                                for (int col = 0; col < width; col ++)
99
                                        try {
100
                                                process(col, row);
101
                                        }catch (ArrayIndexOutOfBoundsException e) {
102
                                        }
103

    
104
                                if (taskEventManager.getEvent() != null)
105
                                        taskEventManager.manageEvent(taskEventManager.getEvent());
106

    
107
                                percent = (row * 100) / height;
108
                        }
109
                percent = 100;
110
                post();
111
        }
112

    
113
        /**
114
         * A?ade un par?metro al filtro
115
         *
116
         * @param name Clave del par?metro
117
         * @param param Objeto pasado como par?metro
118
         */
119
        public void addParam(String name, Object param) {
120
                if (param != null)
121
                        params.put(name, param);
122
                else
123
                        params.remove(name);
124
        }
125

    
126
        /**
127
         * Elimina un par?metro del filtro
128
         * @param name Clave del par?metro a eliminar
129
         */
130
        public void removeParam(String name) {
131
                params.remove(name);
132
        }
133

    
134
        /**
135
         * Obtiene un par?metro a partir de la clave
136
         * @param name Par?metro
137
         * @return Par?metro
138
         */
139
        public Object getParam(String name) {
140
                return params.get(name);
141
        }
142

    
143
        public Hashtable<String, Object> getParams() {
144
                return params;
145
        }
146

    
147
        public void setParams(Hashtable<String, Object> params) {
148
                this.params = params;
149
        }
150

    
151
        public void setExtent(Extent extent) {
152
                this.extent = extent;
153
        }
154
        
155
        public boolean isToConvertToRGB() {
156
                return false;
157
        }
158

    
159
        /**
160
         * Obtiene true si el filtro va a ser ejecutado o false si no va a serlo
161
         * @return
162
         */
163
        public boolean isExec() {
164
                return exec;
165
        }
166

    
167
        /**
168
         * Asigna el valor a la variable exec. Esta estar? a true si el filtro se ejecutar? la pr?xima
169
         * vez que se repinte o false si no se ejecuta.
170
         * @param exec
171
         */
172
        public void setExec(boolean exec) {
173
                this.exec = exec;
174
        }
175

    
176
        /**
177
         * Pone a cero el contador del porcentaje del proceso de filtrado
178
         * @return
179
         */
180
        public void resetPercent() {
181
                percent = 0;
182
        }
183

    
184
        /**
185
         * Obtiene el porcentaje recorrido del proceso de filtrado
186
         * @return
187
         */
188
        public int getPercent() {
189
                return percent;
190
        }
191
        
192
        /*public int[] getRenderBands() {
193
                return renderBands;
194
        }*/
195

    
196
        /**
197
         * Funci?n que contiene el c?digo a ejecutar despues de aplicar el filtro
198
         */
199
        abstract public void post();
200

    
201
        /**
202
         * Ejecuci?n del filtro para un pixel de la imagen
203
         */
204
        abstract public void process(int x, int y);
205

    
206
        /**
207
         * Obtiene el tipo de datos del raster de entrada
208
         */
209
        abstract public int getInRasterDataType();
210

    
211
        /**
212
         * Obtiene el tipo de datos del raster de salida
213
         */
214
        abstract public int getOutRasterDataType();
215

    
216
        /**
217
         * Gets the result of this filter
218
         */
219
        public Object getResult(String name) {
220
                if (name.equals(RESULT_BUFFER)) {
221
                        if (exec)
222
                                return (Object) this.rasterResult;
223
                        else
224
                                return (Object) this.raster;
225
                }
226

    
227
                if (name.equals(RESULT_TRANSPARENCY)) {
228
                        if(transparency == null)
229
                                return null;
230
                        ColorInterpretation ci = null;
231
                        if(rasterResult.getDataType() == Buffer.TYPE_BYTE) {
232
                                if(argbOutput || (rasterResult.getBandCount() == 4 && hasInputTransparency())) {
233
                                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
234
                                                        new String[]{ColorInterpretation.RED_BAND,
235
                                                                        ColorInterpretation.GREEN_BAND,
236
                                                                        ColorInterpretation.BLUE_BAND,
237
                                                                        ColorInterpretation.ALPHA_BAND});
238
                                        transparency.setColorInterpretation(ci);
239
                                        transparency.activeTransparency();
240
                                        return transparency;
241
                                } else if(rasterResult.getBandCount() == 3) {
242
                                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
243
                                                        new String[]{ColorInterpretation.RED_BAND,
244
                                                                        ColorInterpretation.GREEN_BAND,
245
                                                                        ColorInterpretation.BLUE_BAND});
246
                                        transparency.setColorInterpretation(ci);
247
                                        transparency.activeTransparency();
248
                                        return transparency;
249
                                } else if(rasterResult.getBandCount() == 1) {
250
                                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
251
                                                        new String[]{ColorInterpretation.GRAY_BAND});
252
                                        transparency.setColorInterpretation(ci);
253
                                        transparency.activeTransparency();
254
                                        return transparency;
255
                                }
256
                                /*else if(rasterResult.getBandCount() == 3 && renderBands != null && renderBands.length >=3) {
257
                                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(renderBands);
258
                                        transparency.setColorInterpretation(ci);
259
                                        transparency.activeTransparency();
260
                                        return transparency;
261
                                }*/
262
                        } 
263
                        String[] values = new String[rasterResult.getBandCount()];
264
                        for (int i = 0; i < values.length; i++) {
265
                                values[i] = ColorInterpretation.UNDEF_BAND;
266
                        }
267
                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(values);
268
                        transparency.setColorInterpretation(ci);
269
                        transparency.activeTransparency();
270
                        return transparency;
271
                }
272
                return null;
273
        }
274
        
275
        abstract public String getGroup();
276
        abstract public Params getUIParams(String nameFilter);
277
        abstract public String[] getNames();
278

    
279
        public boolean isVisible() {
280
                return true;
281
        }
282

    
283
        public Object clone() throws CloneNotSupportedException {
284
                return super.clone();
285
        }
286

    
287
        public String getName() {
288
                return fName;
289
        }
290

    
291
        public void setName(String name) {
292
                fName = name;
293
        }
294

    
295
        public TreeMap<String, Object> getEnv() {
296
                return environment;
297
        }
298

    
299
        public void setEnv(TreeMap<String, Object> env) {
300
                this.environment = env;
301
        }
302

    
303
        public String getManagerName() {
304
                return managername;
305
        }
306

    
307
        /**
308
         * Releases buffer resources
309
         */
310
        public void dispose() {
311
                
312
        }
313
        
314
        protected Buffer getOutputBuffer() {
315
                return rasterResult;
316
        }
317
        
318
        protected Buffer getInputBuffer() {
319
                return raster;
320
        }
321
        
322
        protected void finalize() throws Throwable {
323
                rasterResult = null;
324
                raster = null;
325
                extent = null;
326
                fName = null;
327
                super.finalize();
328
        }
329

    
330
        /**
331
         * Code to execute before apply a filter
332
         */
333
        public void pre() throws FilterAddException {
334
                exec = true;
335
                raster = (Buffer) params.get("raster");
336
                //renderBands = (int[]) params.get("renderBands");
337
                transparency = (Transparency)environment.get("Transparency");
338
                height = raster.getHeight();
339
                width = raster.getWidth();
340
                
341
                //?til para imagenes de tipo byte que puedan traer transparencia
342
                if(        raster != null && 
343
                        transparency != null && 
344
                        raster.getDataType() == Buffer.TYPE_BYTE &&
345
                        transparency.existAlphaBand()) {
346
                        nBandsToProcess = raster.getBandCount() - 1;
347
                        hasInputTransparency = true;
348
                } else
349
                        nBandsToProcess = raster.getBandCount();
350
        }
351
        
352
        //*****************************************
353
        //Support methods
354
        //*****************************************
355
        
356
        protected void createARGBBufferResult() throws FilterAddException {
357
                BufferParam param = RasterLocator.getManager().getBufferFactory().createBufferParams(width, height, 4, Buffer.TYPE_BYTE, true);
358
                try {
359
                        rasterResult = RasterLocator.getManager().getBufferFactory().createBuffer(param);
360
                        if(raster != null)
361
                                rasterResult.setDataExtent(raster.getDataExtent());
362
                        argbOutput = true;
363
                } catch (LocatorException e) {
364
                        throw new FilterAddException("Error creating buffer", e);
365
                } catch (BufferCreationException e) {
366
                        throw new FilterAddException("Error creating buffer", e);
367
                }
368
        }
369
        
370
        protected void createBufferResult(int dataType, int bandCount) throws FilterAddException {
371
                BufferParam param = RasterLocator.getManager().getBufferFactory().createBufferParams(width, height, bandCount, dataType, true);
372
                try {
373
                        rasterResult = RasterLocator.getManager().getBufferFactory().createBuffer(param);
374
                        if(raster != null)
375
                                rasterResult.setDataExtent(raster.getDataExtent());
376
                } catch (LocatorException e) {
377
                        throw new FilterAddException("Error creating buffer", e);
378
                } catch (BufferCreationException e) {
379
                        throw new FilterAddException("Error creating buffer", e);
380
                }
381
        }
382
        
383
        /**
384
         * Checks the renderBands array for RGB inputs. If it is not good, 
385
         * it will be calculated. This function will have into account the 
386
         * transparency object to render the alpha band
387
         */
388
        /*protected void checkRGBRenderBands() {
389
                for (int i = 0; i < renderBands.length; i++) {
390
                        if(renderBands[i] >= raster.getBandCount())
391
                                renderBands[i] = -1;
392
                }
393
                
394
                //Necesita 3 bandas para renderizar, ya que la entrada debe ser un valor RGB
395
                int countBandsToDraw = 0;
396
                for (int i = 0; i < renderBands.length; i++) {
397
                        if(renderBands[i] >= 0 && renderBands[i] < 3)
398
                                countBandsToDraw ++;
399
                }
400
                //Si no tiene al menos 3 bandas de entrada calculamos el renderBands
401
                if(renderBands == null || countBandsToDraw < 3) {
402
                        switch (raster.getBandCount()) {
403
                        case 1:renderBands = new int[]{0, 0, 0}; break;
404
                        case 2:renderBands = new int[]{0, 1, 1}; break;
405
                        case 3:renderBands = new int[]{0, 1, 2}; break;
406
                        default:
407
                                if(transparency.existAlphaBand())
408
                                        renderBands = new int[]{0, 1, 2, 3}; 
409
                                else
410
                                        renderBands = new int[]{0, 1, 2};
411
                        }
412
                }
413
        }*/
414
        
415
        /**
416
         * Copies the alpha band from the input raster to the output.
417
         * In most filters, this band is not processed and it will copy
418
         * it directly in the output
419
         */
420
        protected void writeAlphaBand(int line, int col) {
421
                if(hasInputTransparency)  {
422
                        rasterResult.setElem(line, col, rasterResult.getBandCount() - 1, 
423
                                        raster.getElemByte(line, col, raster.getBandCount() - 1));
424
                }
425
        }
426
        
427
        protected boolean hasInputTransparency() {
428
                return hasInputTransparency;
429
        }
430
        
431
        protected int numberOfBandsToProcess() {
432
                return nBandsToProcess;
433
        }
434
        
435
        protected ColorInterpretation getColorInterpretation() {
436
                if(transparency != null)
437
                        return transparency.getColorInterpretation();
438
                
439
                if(raster.getBandCount() >= 4)
440
                        return RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
441
                                        new String[]{ColorInterpretation.RED_BAND,
442
                                                ColorInterpretation.GREEN_BAND,
443
                                                ColorInterpretation.BLUE_BAND,
444
                                                ColorInterpretation.ALPHA_BAND});
445
                else if(raster.getBandCount() == 3)
446
                        return RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
447
                                        new String[]{ColorInterpretation.RED_BAND,
448
                                                        ColorInterpretation.GREEN_BAND,
449
                                                        ColorInterpretation.BLUE_BAND});
450
                else return RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
451
                                new String[]{ColorInterpretation.GRAY_BAND});
452
        }
453
}