Statistics
| Revision:

root / branches / v10+Piloto / libraries / libCq_CMS_praster / src / org / cresques / px / PxRaster.java @ 9700

History | View | Annotate | Download (57.5 KB)

1
/*
2
 * Cresques Mapping Suite. Graphic Library for constructing mapping applications.
3
 *
4
 * Copyright (C) 2004-5.
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., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
19
 *
20
 * For more information, contact:
21
 *
22
 * cresques@gmail.com
23
 */
24
package org.cresques.px;
25

    
26
import java.awt.Color;
27
import java.awt.Component;
28
import java.awt.Graphics2D;
29
import java.awt.Image;
30
import java.awt.geom.AffineTransform;
31
import java.awt.geom.GeneralPath;
32
import java.awt.geom.NoninvertibleTransformException;
33
import java.awt.geom.Point2D;
34
import java.awt.image.BufferedImage;
35
import java.awt.image.DataBuffer;
36
import java.awt.image.ImageObserver;
37
import java.util.ArrayList;
38
import java.util.Date;
39
import java.util.Vector;
40

    
41
import org.cresques.cts.ICoordTrans;
42
import org.cresques.cts.IProjection;
43
import org.cresques.filter.RasterFilterStack;
44
import org.cresques.filter.RasterFilterStackManager;
45
import org.cresques.filter.bands.PaletteFilter;
46
import org.cresques.filter.bands.PaletteStackManager;
47
import org.cresques.filter.bands.RasterByteToImageFilter;
48
import org.cresques.filter.bands.RasterDoubleToImageFilter;
49
import org.cresques.filter.bands.RasterFloatToImageFilter;
50
import org.cresques.filter.bands.RasterIntToImageFilter;
51
import org.cresques.filter.bands.RasterShortToImageFilter;
52
import org.cresques.filter.bands.RasterToImageFilter;
53
import org.cresques.filter.enhancement.TransparencyRange;
54
import org.cresques.geo.Projected;
55
import org.cresques.geo.ViewPortData;
56
import org.cresques.io.EcwFile;
57
import org.cresques.io.GdalFile;
58
import org.cresques.io.GeoRasterFile;
59
import org.cresques.io.data.RasterBuf;
60
import org.cresques.io.datastruct.Statistic;
61
import org.cresques.io.exceptions.SupersamplingNotSupportedException;
62

    
63

    
64
/**
65
 *
66
 * @author Luis W. Sevilla (sevilla_lui@gva.es)
67
 * @author Nacho Brodin (brodin_ign@gva.es)
68
 *
69
 */
70
public class PxRaster extends PxObj implements Projected {
71
    protected GeoRasterFile[] geoFile = null;
72
    protected ImageObserver component = null;
73
    Vector pts = null;
74

    
75
    // Soporte para n bandas, visibles de 3 en 3, en ficheros separados
76
    //protected GeoRasterFile [] colorBand = null;
77
    protected int rBand = 1;
78

    
79
    // Soporte para n bandas, visibles de 3 en 3, en ficheros separados
80
    //protected GeoRasterFile [] colorBand = null;
81
    protected int gBand = 2;
82

    
83
    // Soporte para n bandas, visibles de 3 en 3, en ficheros separados
84
    //protected GeoRasterFile [] colorBand = null;
85
    protected int bBand = 3;
86
    public Statistic stats = new Statistic();
87
    int transparente = 0x10ffff80;
88
    String vName = null;
89
    protected boolean pintaMarco = false; //true;
90
    IProjection proj = null;
91
    protected Extent extentOrig = null;
92
    ICoordTrans rp = null;
93
    public RasterFilterStack filterStack = new RasterFilterStack(stats);
94
    private BandSwitch bandSwitch = new BandSwitch();
95
    private boolean firstPxRaster = true;
96
    private final double percentFilterInit = 0.02;
97
    private RasterFilterStackManager stackManager = null;
98
    private Image geoImage = null;
99
    private ViewPortData lastViewPort = null;
100

    
101
    /**
102
     * Variable usada por el draw para calcular el n?mero de pixeles a leer de un
103
     * raster rotado. 
104
     */
105
    private double[] adjustedRotedExtent = null;
106
    
107
    /**
108
     * Constructor.
109
     * @param component
110
     */
111
    public PxRaster(ImageObserver component) {
112
        this.component = component;
113
    }
114

    
115
    /**
116
     * Contructor para un solo fichero
117
     * @param proj        Proyeccci?n
118
     * @param fname Nombre del fichero
119
     * @param component
120
     */
121
    public PxRaster(IProjection proj, String fname, ImageObserver component) {
122
        geoFile = new GeoRasterFile[1];
123
        geoFile[0] = GeoRasterFile.openFile(proj, fname); //loadECW(fname);
124
        geoFile[0].setUpdatable((Component) component);
125
        this.proj = proj;
126
        this.component = component;
127
        setExtent(geoFile[0].getExtent());
128
        setExtentForRequest(geoFile[0].getExtentForRequest());
129
        geoFile[0].setView(geoFile[0].getExtent());
130
        extentOrig = extent;
131
        bandSwitch.addFile(geoFile[0]);
132

    
133
        if (geoFile[0].getBandCount() >= 3) {
134
            setBand(GeoRasterFile.RED_BAND, 0);
135
            setBand(GeoRasterFile.GREEN_BAND, 1);
136
            setBand(GeoRasterFile.BLUE_BAND, 2);
137
        } else if (geoFile[0].getBandCount() == 2) {
138
            setBand(GeoRasterFile.RED_BAND, 0);
139
            setBand(GeoRasterFile.GREEN_BAND, 1);
140
            setBand(GeoRasterFile.BLUE_BAND, 1);
141
        } else if (geoFile[0].getBandCount() == 1) {
142
            //setBand(GeoRasterFile.RED_BAND|GeoRasterFile.GREEN_BAND|GeoRasterFile.BLUE_BAND, 0);
143
            setBand(GeoRasterFile.RED_BAND, 0);
144
            setBand(GeoRasterFile.GREEN_BAND, 0);
145
            setBand(GeoRasterFile.BLUE_BAND, 0);
146
        }
147
    }
148

    
149
    /**
150
     * Constructor para multiples ficheros
151
     */
152
    public PxRaster(IProjection proj, String[] fnames, ImageObserver component) {
153
        this.proj = proj;
154
        this.component = component;
155
        geoFile = new GeoRasterFile[fnames.length];
156

    
157
        for (int i = 0; i < geoFile.length; i++) {
158
            geoFile[i] = GeoRasterFile.openFile(proj, fnames[i]); //loadECW(fname);
159
            geoFile[i].setUpdatable((Component) component);
160
            setExtent(geoFile[i].getExtent());
161
            setExtentForRequest(geoFile[i].getExtentForRequest());
162
            geoFile[i].setView(geoFile[i].getExtent());
163
            bandSwitch.addFile(geoFile[i]);
164
        }
165

    
166
        //geoFile = geoFile[0];
167
        extentOrig = extent;
168

    
169
        if ((fnames.length >= 3) || (geoFile[0].getBandCount() > 2)) {
170
            setBand(GeoRasterFile.RED_BAND, 0);
171
            setBand(GeoRasterFile.GREEN_BAND, 1);
172
            setBand(GeoRasterFile.BLUE_BAND, 2);
173
        } else {
174
            setBand(GeoRasterFile.RED_BAND | GeoRasterFile.GREEN_BAND |
175
                    GeoRasterFile.BLUE_BAND, 0);
176
        }
177
    }
178

    
179
    public PxRaster(GeoRasterFile eFile, ImageObserver component, Extent view) {
180
        geoFile = new GeoRasterFile[1];
181
        geoFile[0] = eFile; //loadECW(fname);
182
        geoFile[0].setUpdatable((Component) component);
183
        setProjection(geoFile[0].getProjection());
184
        this.component = component;
185

    
186
        setExtent(geoFile[0].getExtent());
187
        setExtentForRequest(geoFile[0].getExtentForRequest());
188
        if(view != null){
189
                geoFile[0].setView(view); //geoFile.getExtent());
190
                extentOrig = extent;
191
                bandSwitch.addFile(eFile);
192
        
193
                if (geoFile[0].getBandCount() >= 3) {
194
                    setBand(GeoRasterFile.RED_BAND, 0);
195
                    setBand(GeoRasterFile.GREEN_BAND, 1);
196
                    setBand(GeoRasterFile.BLUE_BAND, 2);
197
                } else if (geoFile[0].getBandCount() == 2) {
198
                    setBand(GeoRasterFile.RED_BAND, 0);
199
                    setBand(GeoRasterFile.GREEN_BAND, 1);
200
                    setBand(GeoRasterFile.BLUE_BAND, 1);
201
                } else if (geoFile[0].getBandCount() == 1) {
202
                    //setBand(GeoRasterFile.RED_BAND|GeoRasterFile.GREEN_BAND|GeoRasterFile.BLUE_BAND, 0);
203
                    setBand(GeoRasterFile.RED_BAND, 0);
204
                    setBand(GeoRasterFile.GREEN_BAND, 0);
205
                    setBand(GeoRasterFile.BLUE_BAND, 0);
206
                }
207
        }
208
    }
209

    
210
    /**
211
     * A?ade un GeoRasterFile al PxRaster
212
     * @param fileName Nombre del fichero
213
     */
214
    public GeoRasterFile addFile(String fileName) {
215
        if (geoFile != null) {
216
            GeoRasterFile[] listFiles = new GeoRasterFile[geoFile.length + 1];
217

    
218
            for (int i = 0; i < geoFile.length; i++)
219
                listFiles[i] = geoFile[i];
220

    
221
            listFiles[geoFile.length] = GeoRasterFile.openFile(proj, fileName);
222
            listFiles[geoFile.length].setUpdatable((Component) component);
223
            setExtent(listFiles[geoFile.length].getExtent());
224
            setExtentForRequest(listFiles[geoFile.length].getExtentForRequest());
225
            listFiles[geoFile.length].setView(listFiles[geoFile.length].getExtent());
226
            bandSwitch.addFile(listFiles[geoFile.length]);
227
            geoFile = listFiles;
228
            return listFiles[geoFile.length - 1];
229
        } else {
230
            System.err.println("PxRaster.addFile(): Imagen no cargada.");
231
            return null;
232
        }
233
    }
234

    
235
    /**
236
     * Devuelve el Extent de un fichero son necesidad de a?adirlo
237
     * al PxRaster
238
     * @param fileName
239
     * @return
240
     */
241
    public Extent testExtentFile(String fileName) {
242
        GeoRasterFile grf = GeoRasterFile.openFile(proj, fileName);
243

    
244
        return grf.getExtent();
245
    }
246

    
247
    /**
248
     * Obtiene el valor del pixel del Image en la posici?n wcx,wcy
249
     * @param wcx Posici?n x
250
     * @param wcx Posici?n y
251
     * @return valor de pixel
252
     */
253
    public int[] getPixel(double wcx, double wcy) {
254
        if (geoImage != null) {
255
            int ptox = 0;
256
            int ptoy = 0;
257

    
258
            try {
259
                //Extent de la imagen completa
260
                Extent extOrtofoto = geoFile[0].getExtent();
261

    
262
                //Variables q definen el extent del objeto image
263
                double minx = 0;
264

    
265
                //Variables q definen el extent del objeto image
266
                double miny = 0;
267

    
268
                //Variables q definen el extent del objeto image
269
                double maxx = 0;
270

    
271
                //Variables q definen el extent del objeto image
272
                double maxy = 0;
273

    
274
                if (lastViewPort.getExtent().getMin().getX() < extOrtofoto.minX()) {
275
                    minx = extOrtofoto.minX();
276
                } else {
277
                    minx = lastViewPort.getExtent().getMin().getX();
278
                }
279

    
280
                if (lastViewPort.getExtent().getMax().getX() > extOrtofoto.maxX()) {
281
                    maxx = extOrtofoto.maxX();
282
                } else {
283
                    maxx = lastViewPort.getExtent().getMax().getX();
284
                }
285

    
286
                if (lastViewPort.getExtent().getMin().getY() < extOrtofoto.minY()) {
287
                    miny = extOrtofoto.minY();
288
                } else {
289
                    miny = lastViewPort.getExtent().getMin().getY();
290
                }
291

    
292
                if (lastViewPort.getExtent().getMax().getY() > extOrtofoto.maxY()) {
293
                    maxy = extOrtofoto.maxY();
294
                } else {
295
                    maxy = lastViewPort.getExtent().getMax().getY();
296
                }
297

    
298
                //Comprobamos que estemos dentro del extent del Image
299
                if ((wcx < minx) || (wcx > maxx) || (wcy < miny) ||
300
                        (wcy > maxy)) {
301
                    int[] res = { -1, -1, -1, -1 };
302

    
303
                    return res;
304
                }
305

    
306
                //Pasamos a coordenadas del Image las coordenadas del mundo real
307
                int w = ((BufferedImage) geoImage).getWidth();
308
                int h = ((BufferedImage) geoImage).getHeight();
309
                double wcw = maxx - minx;
310
                double wch = maxy - miny;
311
                ptox = (int) (((wcx - minx) * w) / wcw);
312
                ptoy = (int) (((wcy - miny) * h) / wch);
313

    
314
                //Obtenemos el pto seleccionado del Image y extraemos el RGB
315
                int px = ((BufferedImage) geoImage).getRGB(ptox, h - ptoy);
316
                int[] values = new int[4];
317
                values[0] = ((px & 0xff000000) >> 24);
318
                values[1] = ((px & 0x00ff0000) >> 16);
319
                values[2] = ((px & 0x0000ff00) >> 8);
320
                values[3] = (px & 0x000000ff);
321

    
322
                return values;
323
            } catch (ArrayIndexOutOfBoundsException e) {
324
                e.printStackTrace();
325
            }
326
        }
327

    
328
        return null;
329
    }
330

    
331
    /**
332
     * Elimina un GeoRasterFile al PxRaster
333
     * @param finaName Nombre del fichero
334
     */
335
    public GeoRasterFile delFile(String fileName) {
336
        if (geoFile != null) {
337
            Vector grfTemp = new Vector();
338

    
339
            GeoRasterFile grfDelete = null;
340
            
341
            for (int i = 0; i < geoFile.length; i++) {
342
                if (!fileName.endsWith(geoFile[i].getName())) {
343
                    grfTemp.add(geoFile[i]);
344
                }else
345
                        grfDelete = geoFile[i];
346
            }
347

    
348
            GeoRasterFile[] listFiles = new GeoRasterFile[grfTemp.size()];
349

    
350
            for (int i = 0; i < listFiles.length; i++)
351
                listFiles[i] = (GeoRasterFile) grfTemp.get(i);
352

    
353
            //Lo eliminamos del bandSwitch
354
            for (int i = 0; i < geoFile.length; i++) {
355
                if (fileName.endsWith(geoFile[i].getName())) {
356
                    bandSwitch.removeFile(geoFile[i]);
357
                }
358
            }
359

    
360
            geoFile = listFiles;
361
            return grfDelete;
362
        } else {
363
            System.err.println("PxRaster.addFile(): Imagen no cargada.");
364
            return null;
365
        }
366
    }
367

    
368
    /**
369
     * Obtiene el tama?o de bloque
370
     * @return
371
     */
372
    public int getBlockSize() {
373
        return geoFile[0].getBlockSize();
374
    }
375

    
376
    /**
377
     *
378
     * @return
379
     */
380
    public GeoRasterFile[] getGeoFiles() {
381
        return geoFile;
382
    }
383

    
384
    public GeoRasterFile getGeoFile() {
385
        return geoFile[0];
386
    }
387

    
388
    /**
389
     * Obtiene el n?mero de bandas del PxRaster. Si ls longitud de geoFile es 1 quiere
390
     * decir que hay un solo fichero que contiene todas las bandas. Si hay m?s de un geoFile
391
     * el n?mero de bandas ser? la suma de todas las bandas de las im?genes que forman
392
     * el geoFile
393
     * @return N?mero de bandas
394
     */
395
    public int getBandCount() {
396
        return bandSwitch.getBandCount();
397
    }
398

    
399
    /**
400
     * Obtiene el tipo de dato del primer GeoRasterFile
401
     * @return
402
     */
403
    public int getDataType() {
404
        if (geoFile != null) {
405
            return geoFile[0].getDataType();
406
        } else {
407
            System.err.println("PxRaster.getDataType(): Imagen no cargada.");
408
        }
409

    
410
        return 0;
411
    }
412

    
413
    /**
414
     * Obtiene el vector de GeoRasterFile que componen el PxRaster
415
     * @return vector GeoRasterFile
416
     */
417
    public GeoRasterFile[] getFiles() {
418
        return geoFile;
419
    }
420

    
421
    /**
422
     * Asocia un colorBand al rojo, verde o azul.
423
     * @param flag cual (o cuales) de las bandas.
424
     * @param nBand        que colorBand
425
     */
426
    public void setBand(int flag, int nBand) {
427
        bandSwitch.setBand(flag, nBand);
428
    }
429

    
430
    /**
431
     * Obtiene la posici?n del fichero asignado a la banda
432
     * que se le pasa por par?metro
433
     * @return
434
     */
435
    public int getPosFile(int flag) {
436
        if (flag == GeoRasterFile.RED_BAND) {
437
            return bandSwitch.getBandR().getPos();
438
        } else if (flag == GeoRasterFile.GREEN_BAND) {
439
            return bandSwitch.getBandG().getPos();
440
        } else if (flag == GeoRasterFile.BLUE_BAND) {
441
            return bandSwitch.getBandB().getPos();
442
        } else {
443
            return -1;
444
        }
445
    }
446

    
447
    /**
448
     * Devuelve el colorBand activo en la banda especificada.
449
     * @param flag banda.
450
     */
451
    public int getBand(int flag) {
452
        if (flag == GeoRasterFile.RED_BAND) {
453
            return bandSwitch.getBandR().getBand();
454
        } else if (flag == GeoRasterFile.GREEN_BAND) {
455
            return bandSwitch.getBandG().getBand();
456
        } else if (flag == GeoRasterFile.BLUE_BAND) {
457
            return bandSwitch.getBandB().getBand();
458
        } else {
459
            return -1;
460
        }
461
    }
462

    
463
    /**
464
     * @param pm
465
     */
466
    public void setDrawBorder(boolean pm) {
467
        pintaMarco = pm;
468
    }
469

    
470
    /**
471
     * Obtiene el nombre del fichero si solo hay uno
472
     * @return Nombre del fichero
473
     */
474
    public String getFName() {
475
        return geoFile[0].getName();
476
    }
477

    
478
    /**
479
     * Obtiene el nombre del fichero GeoRasterFile seleccionado
480
     * @param i        posici?n del GeoRasterFile
481
     * @return Nombre del fichero
482
     */
483
    public String getFName(int i) {
484
        if (geoFile != null) {
485
            if (i < geoFile.length) {
486
                return geoFile[i].getName();
487
            } else {
488
                return null;
489
            }
490
        } else {
491
            System.err.println("PxRaster.getFName(): Imagen no cargada.");
492

    
493
            return null;
494
        }
495
    }
496

    
497
    /**
498
     * Obtiene una lista de Strings con los nombres de todos los ficheros
499
     * que tiene el PxRaster
500
     * @return Lista de nombres
501
     */
502
    public String[] getLisName() {
503
        if (geoFile != null) {
504
            String[] list = new String[geoFile.length];
505

    
506
            for (int i = 0; i < geoFile.length; i++)
507
                list[i] = geoFile[i].getName();
508

    
509
            return list;
510
        } else {
511
            System.err.println("PxRaster.getListName(): Imagen no cargada.");
512

    
513
            return null;
514
        }
515
    }
516

    
517
    /**
518
     * Devuelve la anchura total del fichero, en pixeles.
519
     * @return ancho en pixeles
520
     */
521
    public int getFWidth() {
522
        if (geoFile != null) {
523
            return geoFile[0].getWidth();
524
        } else {
525
            System.err.println("PxRaster.getFWidth(): Imagen no cargada.");
526

    
527
            return 0;
528
        }
529
    }
530

    
531
    /**
532
     * Devuelve la anchura total del fichero, en pixeles.
533
     * @return ancho en pixeles
534
     */
535
    public int getFWidth(int i) {
536
        if (i < geoFile.length) {
537
            return geoFile[i].getWidth();
538
        } else {
539
            System.err.println("PxRaster.getFWidth(): Imagen no cargada.");
540

    
541
            return 0;
542
        }
543
    }
544

    
545
    /**
546
     * Devuelve la altura total del fichero, en pixeles.
547
     * @return alto en pixeles
548
     */
549
    public int getFHeight() {
550
        if (geoFile != null) {
551
            return geoFile[0].getHeight();
552
        } else {
553
            System.err.println("PxRaster.getFHeight(): Imagen no cargada.");
554

    
555
            return 0;
556
        }
557
    }
558

    
559
    /**
560
     * Devuelve la altura total del fichero, en pixeles.
561
     * @return alto en pixeles
562
     */
563
    public int getFHeight(int i) {
564
        if (i < geoFile.length) {
565
            return geoFile[i].getHeight();
566
        } else {
567
            System.err.println("PxRaster.getFHeight(): Imagen no cargada.");
568

    
569
            return 0;
570
        }
571
    }
572

    
573
    /**
574
     * Devuelve el n?mero de ficheros que componen el PxRaster
575
     * @return N?mero de ficheros
576
     */
577
    public int nFiles() {
578
        if (geoFile != null) {
579
            return geoFile.length;
580
        } else {
581
            return 0;
582
        }
583
    }
584

    
585
    /**
586
     * Activa o desactiva la transparencia de los ficheros que forman el PxRaster
587
     * @param t true o false para activar o desactivar transparencia
588
     */
589
    public void setTransparency(boolean t) {
590
        if (geoFile != null) {
591
            for (int i = 0; i < geoFile.length; i++) {
592
                geoFile[i].setTransparency(t);
593
            }
594
        } else {
595
            System.err.println("PxRaster.setTransparency(): Imagen no cargada.");
596

    
597
            return;
598
        }
599
    }
600

    
601
    /**
602
     * Pone la transparencia de los ficheros de la imagen a un valor
603
     * @param t Valor para la transparencia
604
     */
605
    public void setTransparency(int t) {
606
        if (geoFile != null) {
607
            for (int i = 0; i < geoFile.length; i++) {
608
                geoFile[i].setTransparency(t);
609
            }
610
        } else {
611
            System.err.println("PxRaster.setTransparency(): Imagen no cargada.");
612

    
613
            return;
614
        }
615
    }
616

    
617
    /**
618
     * Obtiene el alpha del primer fichero. Han de ser iguales en todos
619
     * los ficheros de la imagen.
620
     * @return alpha
621
     */
622
    public int getAlpha() {
623
        if (geoFile != null) {
624
            return geoFile[0].getAlpha();
625
        } else {
626
            System.err.println("PxRaster.getAlpha(): Imagen no cargada.");
627

    
628
            return 0;
629
        }
630
    }
631

    
632
    /**
633
     * Asigna el extent completo del raster. Este contiene las coordenadas reales tanto
634
     * para un raster rotado como sin rotar. Este extent coincide con requestExtent
635
     * cuando el raster no tiene rotaci?n.
636
     * @param Extent 
637
     */
638
    public void setExtent(Extent e) {
639
        super.extent = e;
640
        if(e != null){
641
                pts = new Vector();
642
                pts.add(proj.createPoint(e.minX(), e.minY()));
643
                pts.add(proj.createPoint(e.maxX(), e.minY()));
644
                pts.add(proj.createPoint(e.maxX(), e.maxY()));
645
                pts.add(proj.createPoint(e.minX(), e.maxY()));
646
        }
647
    }
648
    
649
    /**
650
     * Asigna el extent sobre el que se ajusta una petici?n para que esta no exceda el 
651
     * extent m?ximo del raster. Para un raster sin rotar ser? igual al extent
652
     * pero para un raster rotado ser? igual al extent del raster como si no 
653
     * tuviera rotaci?n. Esto ha de ser as? ya que la rotaci?n solo se hace sobre la
654
     * vista y las peticiones han de hacerse en coordenadas de la imagen sin shearing
655
     * aplicado.
656
     * @param Extent
657
     */
658
    public void setExtentForRequest(Extent e) {
659
        super.requestExtent = e;
660
        if(e != null){
661
                pts = new Vector();
662
                pts.add(proj.createPoint(e.minX(), e.minY()));
663
                pts.add(proj.createPoint(e.maxX(), e.minY()));
664
                pts.add(proj.createPoint(e.maxX(), e.maxY()));
665
                pts.add(proj.createPoint(e.minX(), e.maxY()));
666
        }
667
    }
668

    
669
    /**
670
     * Cambia la vista (viewport) sobre el raster.
671
     *
672
     * @param v extent
673
     * @param vName nombre
674
     */
675
    public void setView(Extent v, String vName) {
676
        if (geoFile != null) {
677
            for (int i = 0; i < geoFile.length; i++) {
678
                geoFile[i].setView(v);
679
            }
680
        } else {
681
            System.err.println("PxRaster.setView(): Imagen no cargada.");
682

    
683
            return;
684
        }
685

    
686
        this.vName = vName;
687
    }
688

    
689
    /**
690
     * Obtiene la escala.
691
     *
692
     * @param width
693
     * @param height
694
     * @return
695
     */
696
    public double[] getScale(int width, int height) {
697
        double[] scale = new double[2];
698

    
699
        if (geoFile != null) {
700
            scale[0] = ((double) width) / geoFile[0].getView().width();
701
            scale[1] = ((double) height) / geoFile[0].getView().height();
702

    
703
            return scale;
704
        } else {
705
            System.err.println("PxRaster.getScale(): Imagen no cargada.");
706

    
707
            return null;
708
        }
709
    }
710

    
711
    /**
712
     * Transforma la petici?n que est? en coordenadas de la imagen sin rotar a coordenadas de la imagen rotada
713
     * para que sea posible el calculo de la caja m?nima de inclusi?n. La coordenada superior izquierda de esta
714
     * ser? la que se use para posicionar la imagen sobre el graphics aplicandole la transformaci?n de la la vista.
715
     * @param v
716
     * @return
717
     */
718
    private Point2D coordULRotateRaster(double[] v){
719
        double vx = v[0];
720
        double vy = v[1];
721
        double vx2 = v[2];
722
        double vy2 = v[3];
723
            if (geoFile != null) {
724
                double[] transf = geoFile[0].getTransform();
725
                                
726
                   if(transf != null && (transf[2] != 0 || transf[4] != 0)){
727
                           //La transformaci?n se hace en base a una esquina que varia con el signo del 
728
                           //pixel size. 
729
                           double ptoDesplX = (transf[1] > 0)?requestExtent.minX():requestExtent.maxX();
730
                    double ptoDesplY = (transf[5] < 0)?requestExtent.maxY():requestExtent.minY();
731
            
732
                    Point2D ul = new Point2D.Double(vx - ptoDesplX, vy2 - ptoDesplY);
733
                    Point2D ur = new Point2D.Double(vx2 - ptoDesplX, vy2 - ptoDesplY);
734
                    Point2D ll = new Point2D.Double(vx - ptoDesplX, vy - ptoDesplY);
735
                    Point2D lr = new Point2D.Double(vx2 - ptoDesplX, vy - ptoDesplY);
736
                    
737
                           double shearX = 0;
738
                double shearY = 0;
739
              
740
                if(transf[5] != 0)
741
                        shearX = transf[2] / transf[5];
742
                else
743
                        shearX = transf[2];
744
                if(transf[1] != 0)
745
                        shearY = transf[4] / transf[1];
746
                else
747
                        shearY = transf[4];
748
                
749
                
750
                        AffineTransform at = new AffineTransform();
751
                        at.setToShear(shearX, shearY);
752

    
753
                        at.transform(ul, ul);
754
                        at.transform(ur, ur);
755
                        at.transform(ll, ll);
756
                        at.transform(lr, lr);
757
                                
758
                        ul = new Point2D.Double(ul.getX() + ptoDesplX, ul.getY() + ptoDesplY);
759
                        ur = new Point2D.Double(ur.getX() + ptoDesplX, ur.getY() + ptoDesplY);
760
                        ll = new Point2D.Double(ll.getX() + ptoDesplX, ll.getY() + ptoDesplY);
761
                        lr = new Point2D.Double(lr.getX() + ptoDesplX, lr.getY() + ptoDesplY);
762
                        
763
                        vx2 = Math.max(Math.max(ul.getX(), ur.getX()), Math.max(ll.getX(), lr.getX()));
764
                        vy2 = Math.max(Math.max(ul.getY(), ur.getY()), Math.max(ll.getY(), lr.getY()));
765
                        vx = Math.min(Math.min(ul.getX(), ur.getX()), Math.min(ll.getX(), lr.getX()));
766
                        vy = Math.min(Math.min(ul.getY(), ur.getY()), Math.min(ll.getY(), lr.getY()));
767
                        adjustedRotedExtent = new double[4];
768
                        adjustedRotedExtent[0] = vx;
769
                        adjustedRotedExtent[1] = vy;
770
                        adjustedRotedExtent[2] = vx2;
771
                        adjustedRotedExtent[3] = vy2;
772
                        return ul;
773
                }
774
                   
775
        }
776
            return null;
777
        
778
    }
779
    
780
    /**
781
     * Ajusta la extensi?n pasada por par?metro y que corresponde al extent de la vista donde
782
     * se va a dibujar a los valores m?ximos y m?nimos de la imagen. Esto sirve para que la
783
     * petici?n al driver nunca sobrepase los l?mites de la imagen tratada aunque la vista
784
     * donde se dibuje sea de mayor tama?o.
785
     * 
786
     * Antes de realizar este ajuste hay que transformar la petici?n que puede corresponder a 
787
     * una imagen rotada a las coordenadas de la imagen sin rotar ya que las peticiones al 
788
     * driver hay que hacerlas con estas coordenadas. Para esto trasladamos la petici?n al origen
789
     * de la imagen (esquina superior izquierda), aplicamos la transformaci?n inversa a las cuatro 
790
     * esquinas obtenidas y volvemos a trasladar a su posici?n original. 
791
     * 
792
     * Se usa la transformaci?n inversa para trasladar un punto del raster rotado al mismo sin 
793
     * rotar y la transformaci?n af?n normal para trasladar un punto sin rotar a uno rotado.
794
     * 
795
     * @param sz Extent completo de la vista donde se va a dibujar.
796
     */
797
    protected double[] calculateNewView(ViewPortData vp) {
798
            Extent sz = vp.getExtent();
799
        double vx = sz.minX();
800
        double vy = sz.minY();
801
        double vx2 = sz.maxX();
802
        double vy2 = sz.maxY();
803
        
804
        //Trasladamos la petici?n si est? rotada a su posici?n sin rotar
805
        
806
        if (geoFile != null) {
807
                double[] transf = geoFile[0].getTransform();
808
                                
809
                   if(transf != null && (transf[2] != 0 || transf[4] != 0)){
810
                           
811
                           //La transformaci?n se hace en base a una esquina que varia con el signo del 
812
                           //pixel size. 
813
                           double ptoDesplX = (transf[1] > 0)?requestExtent.minX():requestExtent.maxX();
814
                    double ptoDesplY = (transf[5] < 0)?requestExtent.maxY():requestExtent.minY();
815
                    
816
                    Point2D ul = new Point2D.Double(vx - ptoDesplX, vy2 - ptoDesplY);
817
                    Point2D ur = new Point2D.Double(vx2 - ptoDesplX, vy2 - ptoDesplY);
818
                    Point2D ll = new Point2D.Double(vx - ptoDesplX, vy - ptoDesplY);
819
                    Point2D lr = new Point2D.Double(vx2 - ptoDesplX, vy - ptoDesplY);
820
                    
821
                           double shearX = 0;
822
                double shearY = 0;
823
                if(transf[5] != 0)
824
                        shearX = transf[2] / transf[5];
825
                else
826
                        shearX = transf[2];
827
                if(transf[1] != 0)
828
                        shearY = transf[4] / transf[1];
829
                else
830
                        shearY = transf[4];
831
                
832
                        AffineTransform at = new AffineTransform();
833
                        at.setToShear(shearX, shearY);
834
                        
835
                        try {
836
                                at.inverseTransform(ul, ul);
837
                                at.inverseTransform(ur, ur);
838
                                at.inverseTransform(ll, ll);
839
                                at.inverseTransform(lr, lr);
840
                                } catch (NoninvertibleTransformException e) {
841
                                        e.printStackTrace();
842
                                }
843
                                
844
                        ul = new Point2D.Double(ul.getX() + ptoDesplX, ul.getY() + ptoDesplY);
845
                        ur = new Point2D.Double(ur.getX() + ptoDesplX, ur.getY() + ptoDesplY);
846
                        ll = new Point2D.Double(ll.getX() + ptoDesplX, ll.getY() + ptoDesplY);
847
                        lr = new Point2D.Double(lr.getX() + ptoDesplX, lr.getY() + ptoDesplY);
848
                        
849
                        vx2 = Math.max(Math.max(ul.getX(), ur.getX()), Math.max(ll.getX(), lr.getX()));
850
                        vy2 = Math.max(Math.max(ul.getY(), ur.getY()), Math.max(ll.getY(), lr.getY()));
851
                        vx = Math.min(Math.min(ul.getX(), ur.getX()), Math.min(ll.getX(), lr.getX()));
852
                        vy = Math.min(Math.min(ul.getY(), ur.getY()), Math.min(ll.getY(), lr.getY()));
853
                }
854
        }
855

    
856
        if (vx < requestExtent.minX())
857
            vx = requestExtent.minX();
858
        
859
        if (vy < requestExtent.minY()) 
860
            vy = requestExtent.minY();
861
        
862
        if (vx2 > requestExtent.maxX()) 
863
            vx2 = requestExtent.maxX();
864
        
865
        if (vy2 > requestExtent.maxY())
866
            vy2 = requestExtent.maxY();
867
                
868
        if (geoFile != null) {
869
            for (int i = 0; i < geoFile.length; i++)
870
                    geoFile[i].setView(new Extent(vx, vy, vx2, vy2));
871
        } else {
872
            System.err.println("PxRaster.calculateNewView(): Imagen no cargada.");
873
        }
874
        double[] adjustedExtent = {vx, vy, vx2, vy2};
875
        return adjustedExtent;
876
    }
877
    
878
    /**
879
     * Aplica transparencia leyendo los metadatos
880
     */
881
    private void setTransparencyByPixel(){
882
            if(geoFile[0].getMetadata() != null){
883
                    if (stackManager == null){
884
                        TransparencyRange[] noData = geoFile[0].getMetadata().parserNodataInMetadata();
885
                        if(noData != null){
886
                        ArrayList entries = new ArrayList();
887
                        for(int i = 0; i < noData.length; i++)
888
                                  entries.add(noData[i]);
889
                        stackManager = new RasterFilterStackManager(filterStack);
890
                        stackManager.addTransparencyFilter(        entries, 0x0, 0xff, 0xff, 0xff);
891
                        }
892
                        TransparencyRange noDataValue = geoFile[0].getMetadata().parserNodataByBand();
893
                        if(noData == null  && noDataValue != null){
894
                        ArrayList entries = new ArrayList();
895
                        entries.add(noDataValue);
896
                        stackManager = new RasterFilterStackManager(filterStack);
897
                        stackManager.addTransparencyFilter(        entries, 0x0, 0xff, 0xff, 0xff);
898
                        }
899
                        
900
                    }
901
        }
902
    }
903
    
904
    /** Dibuja el raster sobre el Graphics. Para ello debemos de pasar el viewPort que corresponde a la
905
     * vista. Este viewPort es ajustado a los tama?os m?ximos y m?nimos de la imagen por la funci?n  
906
     * calculateNewView. Esta funci?n tambi?n asignar? la vista a los drivers. Posteriormente se calcula 
907
     * el alto y ancho de la imagen a dibujar (wImg, hImg), as? como el punto donde se va a pintar dentro 
908
     * del graphics (pt). Finalmente se llama a updateImage del driver para que pinte y una vez dibujado
909
     * se pasa a trav?s de la funci?n renderizeRaster que es la encargada de aplicar la pila de filtros
910
     * sobre el Image que ha devuelto el driver.
911
     * 
912
     * Para calcular en que coordenada pixel (pt) se empezar? a pintar el BufferedImage con el raster le?do
913
     * se aplica sobre la esquina superior izquierda de esta la matriz de transformaci?n del ViewPortData
914
     * pasado vp.mat.transform(pt, pt). Si el raster no est? rotado este punto es el resultante de la
915
     * funci?n calculateNewView que devuelve la petici?n ajustada al extent de la imagen (sin rotar). Si
916
     * el raster est? rotado necesitaremos para la transformaci?n el resultado de la funci?n coordULRotateRaster. 
917
     * Lo que hace esta ?ltima es colocar la petici?n que ha sido puesta en coordenadas de la imagen sin rotar
918
     * (para pedir al driver de forma correcta) otra vez en coordenadas de la imagen rotada (para calcular su 
919
     * posici?n de dibujado).
920
     * 
921
     * Para dibujar sobre el Graphics2D el raster rotado aplicaremos la matriz de transformaci?n con los 
922
     * par?metros de Shear sobre este Graphics de forma inversa. Como hemos movido el fondo tendremos que
923
     * recalcular ahora el punto donde se comienza a dibujar aplicandole la transformaci?n sobre este
924
     * at.inverseTransform(pt, pt);. Finalmente volcamos el BufferedImage sobre el Graphics volviendo a dejar
925
     * el Graphics en su posici?n original al acabar. 
926
     * 
927
     * @param g Graphics sobre el que se pinta
928
     * @param vp ViewPort de la extensi?n a dibujar
929
     */
930
    public synchronized void draw(Graphics2D g, ViewPortData vp) {
931
        geoImage = null;
932
            double shearX = 0;
933
        double shearY = 0;
934
        
935
        long t2;
936
        long t1 = new Date().getTime();
937
        lastViewPort = vp;
938
            
939
        if ((vp.getExtent().minX() > extent.maxX()) ||
940
                (vp.getExtent().minY() > extent.maxY()) ||
941
                (vp.getExtent().maxX() < extent.minX()) ||
942
                (vp.getExtent().maxY() < extent.minY())) {
943
            return;
944
        }
945

    
946
        double[] adjustedExtent = calculateNewView(vp);
947
        Point2D p2d = coordULRotateRaster(adjustedExtent);
948

    
949
        Extent v = geoFile[0].getView();
950
        double x = v.minX();
951
        double y = v.minY();
952
        double w = v.width();
953
        double h = v.height();
954

    
955
        double scalex = vp.mat.getScaleX();
956
        double scaley = vp.mat.getScaleY();
957
        
958
        /*int wImg = (int) Math.round(Math.abs(w * scalex));
959
        int hImg = (int) Math.round(Math.abs(h * scaley));*/
960
        int wImg = (int) Math.round(Math.abs((adjustedExtent[2] - adjustedExtent[0]) * scalex));
961
        int hImg = (int) Math.round(Math.abs((adjustedExtent[3] - adjustedExtent[1]) * scaley));
962

    
963
        if ((wImg <= 0) || (hImg <= 0))
964
            return;
965
        
966
        //Para la transformaci?n usamos el extent que ha ajustado la funci?n calculateNewView y no usamos 
967
        //el getView porque el getView puede haber  sufrido una transformaci?n en caso de que exista 
968
        //fichero .rmf. En caso de no existir este fichero ser?a lo mismo aplicar la funci?n:
969
        //Point2D.Double pt = new Point2D.Double(x, y + h);
970
        int wI = wImg, hI = hImg;
971
        double[] transf = bandSwitch.getBandR().getGeoRasterFile().getTransform();
972
        Point2D.Double pt = null;
973
               if(transf != null && (transf[2] != 0 || transf[4] != 0)){ //Esta rotada
974
                       pt =  new Point2D.Double(p2d.getX(), p2d.getY());
975
                       wImg = (int) Math.round(Math.abs((adjustedRotedExtent[2] - adjustedRotedExtent[0]) * scalex));
976
            hImg = (int) Math.round(Math.abs((adjustedRotedExtent[3] - adjustedRotedExtent[1]) * scaley));
977
               }else{        //No est? rotada
978
                               pt = new Point2D.Double(adjustedExtent[0], adjustedExtent[3]);
979
               }
980
        
981
        try {
982
            vp.mat.transform(pt, pt);
983
            
984
            setTransparencyByPixel();
985
                        
986
            if ((geoFile != null) && geoFile[0] instanceof GdalFile &&
987
                    (geoFile[0].getDataType() != DataBuffer.TYPE_BYTE)) {
988
                    RasterBuf raster = null;
989
                    if (geoFile.length > 1) { // la imagen sale de distintos ficheros
990
                            RasterBuf rasterG=null, rasterB=null;
991
                        raster = ((GdalFile) bandSwitch.getBandR().getGeoRasterFile()).getRaster(wImg, hImg, rp);
992
                        rasterG = ((GdalFile) bandSwitch.getBandG().getGeoRasterFile()).getRaster(wImg, hImg, rp);
993
                        raster.copyBand(rasterG, 0, 1);
994
                        rasterB = ((GdalFile) bandSwitch.getBandB().getGeoRasterFile()).getRaster(wImg, hImg, rp);
995
                        raster.copyBand(rasterB, 0, 2);
996
                    } else { // Toda la imagen est? en el mismo fichero
997
                            raster = ((GdalFile) geoFile[0]).getRaster(wImg, hImg, rp);
998
                    } 
999
                    t2 = new Date().getTime();
1000

    
1001
                System.out.println("Dibujando PxRaster: " + ((t2 - t1) / 1000D) + ", secs. Filtrando/Renderizando");
1002
                t1 = t2;
1003

    
1004
                filterStack.setInitRasterBuf(raster);
1005

    
1006
                //Si la imagen es de 16 bits lleva un filtro de realce por defecto
1007
                if (stackManager == null){
1008
                    stackManager = new RasterFilterStackManager(filterStack);
1009
                    stackManager.addEnhancedFilter(false, geoFile[0].getName());
1010
                    stackManager.removeFilter(stackManager.getTypeFilter("computeminmax"));
1011
                    stackManager.addTailFilter(this.percentFilterInit, 0D, true);
1012
                }
1013
                
1014
                //Para imagenes de una banda replicamos esta en el resto del rasterBuf
1015
                if(raster.getBandCount() == 1){
1016
                        raster.replicateBand(0, 1);
1017
                        raster.replicateBand(0, 2);
1018
                }
1019
                
1020
                geoImage = renderizeRaster(raster, vp, v);
1021
                g.drawImage(geoImage, (int)(pt.getX()), (int)(pt.getY()), component);
1022
            } else if((geoFile != null) && (geoFile.length > 1) && 
1023
                            (!bandSwitch.getBandR().getGeoRasterFile().getName().equals(bandSwitch.getBandG().getGeoRasterFile().getName()) || 
1024
                            !bandSwitch.getBandR().getGeoRasterFile().getName().equals(bandSwitch.getBandB().getGeoRasterFile().getName()) ||
1025
                            !bandSwitch.getBandG().getGeoRasterFile().getName().equals(bandSwitch.getBandB().getGeoRasterFile().getName()))
1026
                            ) { // multiFiles
1027
                System.out.println("Dibujando PxRaster (Multifile) ... Bands " +
1028
                                   geoFile.length);
1029

    
1030
                if (bandSwitch.getBandR().getGeoRasterFile() instanceof EcwFile) {
1031
                    ((EcwFile) bandSwitch.getBandR().getGeoRasterFile()).setMultifile(true);
1032
                }
1033

    
1034
                if (bandSwitch.getBandG().getGeoRasterFile() instanceof EcwFile) {
1035
                    ((EcwFile) bandSwitch.getBandG().getGeoRasterFile()).setMultifile(true);
1036
                }
1037

    
1038
                if (bandSwitch.getBandB().getGeoRasterFile() instanceof EcwFile) {
1039
                    ((EcwFile) bandSwitch.getBandB().getGeoRasterFile()).setMultifile(true);
1040
                }
1041
                
1042
                //TODO:Soluci?n para que no se pinte si hay sharpening. Esto hay que pensarlo mejor
1043
                if (stackManager == null) 
1044
                    stackManager = new RasterFilterStackManager(filterStack);
1045
                if (!filterStack.isActive(stackManager.getTypeFilter("sharpening"))){
1046
                        geoImage = bandSwitch.getBandR().getGeoRasterFile().updateImage(wImg, hImg, rp, null, 0, 0);
1047
                        geoImage = bandSwitch.getBandG().getGeoRasterFile().updateImage(wImg, hImg, rp, geoImage, 
1048
                                                                        bandSwitch.getBandG().getBand(), GeoRasterFile.GREEN_BAND);
1049
                        geoImage = bandSwitch.getBandB().getGeoRasterFile().updateImage(wImg, hImg, rp, geoImage, 
1050
                                                                        bandSwitch.getBandB().getBand(), GeoRasterFile.BLUE_BAND);
1051
                }else{
1052
                        geoImage = new BufferedImage(wImg, hImg, BufferedImage.TYPE_INT_RGB);
1053
                }
1054
                
1055
                filterStack.setInitRasterBuf(geoImage);
1056
                
1057
                geoImage = renderizeRaster(geoImage, vp, v);
1058

    
1059
                g.drawImage(geoImage, (int)(pt.getX()), (int)(pt.getY()), component);
1060
            } else if ((geoFile != null) ) { // Una solo fichero
1061

    
1062
                    geoImage = bandSwitch.getBandR().getGeoRasterFile().updateImage(wImg, hImg, rp, null, 0, 0);
1063
                    
1064
                    if(bandSwitch.getBandR().getGeoRasterFile().getPalette() != null){
1065
                            PaletteFilter pf = (PaletteFilter)filterStack.getByType(PaletteStackManager.palette);
1066
                            if(pf == null){
1067
                                    if (stackManager == null)
1068
                            stackManager = new RasterFilterStackManager(filterStack);
1069
                        PaletteStackManager psm = (PaletteStackManager)stackManager.getManagerByClass(PaletteStackManager.class);
1070
                        stackManager.getFilterStack().removeFilter(PaletteStackManager.palette);
1071
                        
1072
                        /*TODO:
1073
                        * A la funci?n addPaletteFilter se le pasa el valor false al par?metro interpolate, lo cual no ser? v?lido
1074
                        * si se leen rasters con paletas asociadas que puedan especificar si se interpola o no, por ejemplo un rmf 
1075
                        * cuando se dote a estos de la posibilidad de almacenar paletas. Para este cas? hay que buscar la forma de saber
1076
                        * en este punto si la paleta asociada al GeoRasterFile se visualiza con o sin interpolaci?n.  
1077
                        */             
1078
                        psm.addPaletteFilter(bandSwitch.getBandR().getGeoRasterFile().getPalette(),false);
1079
                        
1080
                            }
1081
                    }
1082
                    
1083
                filterStack.setInitRasterBuf(geoImage);
1084

    
1085
                geoImage = renderizeRaster(geoImage, vp, v);
1086
                
1087
                AffineTransform at = new AffineTransform();
1088

    
1089
                if(transf != null && (transf[2] != 0 || transf[4] != 0)){
1090
                                                
1091
                        //Obtenemos los par?metros de shearing
1092
                        if(transf[5] != 0)
1093
                                shearX = transf[2] / transf[5];
1094
                        else
1095
                                shearX = transf[2];
1096
                        if(transf[1] != 0)
1097
                                shearY = transf[4] / transf[1];
1098
                        else
1099
                                shearY = transf[4];
1100
                        
1101
                        //Aplicamos el shear a la vista
1102
                                at.setToShear(-shearX, -shearY);
1103
                                
1104
                                //Escalamos en pixeles la misma cantidad que hemos le?do de m?s.  
1105
                                at.scale(((double)wI/(double)wImg), ((double)hI/(double)hImg));
1106
                                                                                                                      
1107
                                g.transform(at);
1108
                                
1109
                                //Aplicamos el shear inverso al punto donde se comienza a dibujar
1110
                                at.inverseTransform(pt, pt);
1111
                                
1112
                                g.drawImage(geoImage, (int) (pt.getX()), (int) (pt.getY()), component);
1113
                                g.transform(at.createInverse());
1114
                }else
1115
                        g.drawImage(geoImage, (int) (pt.getX()), (int) (pt.getY()), component);
1116
               
1117
            } else { // no cargada
1118
                System.err.println("Dibujando PxRaster: Foto no cargada.");
1119
            }
1120
            
1121
            t2 = new Date().getTime();
1122
            System.out.println("Dibujando PxRaster: " + ((t2 - t1) / 1000D) + ", secs.");
1123
        }catch (SupersamplingNotSupportedException e) {
1124
            System.err.println("Supersampling not supported");
1125
            return;
1126
        }catch (Exception e) {
1127
            e.printStackTrace();
1128
        }
1129
        
1130
        if (pintaMarco) {
1131
            drawMarco(g, vp);
1132
        }
1133
    }
1134

    
1135
    /**
1136
     * Aplica la pila de fitros sobre el RasterBuf pasado como par?metro
1137
     * y lo devuelve en Image
1138
     * @param raster        RasterBuf con la imagen sobre la que se aplicaran filtros
1139
     * @return        Image con la imagen con los filtros puestos
1140
     */
1141
    public Image renderizeRaster(RasterBuf raster, ViewPortData vp, Extent e) {
1142
        if (filterStack != null) {
1143
                filterStack.setViewPortData(vp);
1144
                filterStack.setExtent(e);
1145
                filterStack.setStep(geoFile[0].getStepX(), geoFile[0].getStepY());
1146
            raster = filterStack.execute(raster);
1147
        }
1148
        System.out.println("Image renderizeRaster(RasterBuf raster, ViewPortData vp) ");
1149
        //Aplicamos el filtro para convertir a Image
1150
        
1151
        RasterToImageFilter rti = null;
1152
        if(getDataType() == RasterBuf.TYPE_BYTE){
1153
                rti = new RasterByteToImageFilter();        
1154
        }else if(getDataType() == RasterBuf.TYPE_SHORT){
1155
                rti = new RasterShortToImageFilter();
1156
        }else if(getDataType() == RasterBuf.TYPE_INT){
1157
                rti = new RasterIntToImageFilter();
1158
        }else if(getDataType() == RasterBuf.TYPE_FLOAT){
1159
                rti = new RasterFloatToImageFilter();
1160
        }else if(getDataType() == RasterBuf.TYPE_DOUBLE){
1161
                rti = new RasterDoubleToImageFilter();
1162
        }
1163
        
1164
        
1165
        //rti.addParam("raster", raster);
1166
        if (filterStack.getOutDataType()!= RasterBuf.TYPE_IMAGE){
1167
                rti.addParam("raster", filterStack.getResult());
1168
                rti.addParam("alpha", new Integer(this.getAlpha()));
1169
                rti.execute();
1170
                raster = null;
1171
                return (Image) rti.getResult("raster");
1172
        }
1173
        else
1174
                return (Image)filterStack.getResult();
1175
    }
1176

    
1177
    /**
1178
     * Aplica la pila de filtros sobre el Image pasado como par?metro y lo devuelve.
1179
     * Si la salida del ?ltimo filtro es un RasterBuf lo convertir? a Image
1180
     * @param image Image con la imagen sobre la que se aplicaran filtros
1181
     * @return        Image con la imagen con los filtros puestos
1182
     */
1183
    public Image renderizeRaster(Image image, ViewPortData vp, Extent e) {
1184
        if (filterStack != null) {
1185
                filterStack.setViewPortData(vp);
1186
                filterStack.setExtent(e);
1187
                filterStack.setStep(geoFile[0].getStepX(), geoFile[0].getStepY());
1188
            filterStack.execute(image);
1189
        }
1190
      
1191
        if (filterStack.getOutDataType() != RasterBuf.TYPE_IMAGE) {
1192
            //Aplicamos el filtro para convertir a Image
1193
                
1194
                     RasterToImageFilter rti = null;
1195
                 if(getDataType() == RasterBuf.TYPE_BYTE){
1196
                         rti = new RasterByteToImageFilter();        
1197
                 }else if(getDataType() == RasterBuf.TYPE_SHORT){
1198
                         rti = new RasterShortToImageFilter();
1199
                 }else if(getDataType() == RasterBuf.TYPE_INT){
1200
                         rti = new RasterIntToImageFilter();
1201
                 }else if(getDataType() == RasterBuf.TYPE_FLOAT){
1202
                         rti = new RasterFloatToImageFilter();
1203
                 }else if(getDataType() == RasterBuf.TYPE_DOUBLE){
1204
                         rti = new RasterDoubleToImageFilter();
1205
                 }
1206
          
1207
            //RasterIntToImageFilter rti = new RasterIntToImageFilter();
1208
            
1209
                 rti.addParam("raster", (RasterBuf) filterStack.getResult());
1210
                 rti.addParam("alpha", new Integer(this.getAlpha()));
1211
                 rti.execute();
1212
         
1213
                 return (Image) rti.getResult("raster");
1214
        }        
1215
        return (Image) filterStack.getResult();
1216
       // return image;
1217
    }
1218

    
1219
    /**
1220
     *
1221
     * @param g
1222
     * @param vp
1223
     */
1224
    public void drawMarco(Graphics2D g, ViewPortData vp) {
1225
        //                Color color = new Color(255,222,165,128), fillColor = new Color(255,214,132,128);
1226
        Color color = new Color(128, 128, 128);
1227

    
1228
        //                Color color = new Color(255,222,165,128), fillColor = new Color(255,214,132,128);
1229
        Color fillColor = new Color(255, 220, 220, 0x20);
1230
        GeneralPath gp = newGP(vp);
1231
        g.setColor(fillColor);
1232
        g.fill(gp);
1233
        g.setColor(color);
1234
        g.draw(gp);
1235
    }
1236

    
1237
    private GeneralPath newGP(ViewPortData vp) {
1238
        //if (gp != null) return;
1239
        GeneralPath gp = new GeneralPath();
1240
        Point2D.Double pt0 = new Point2D.Double(0.0, 0.0);
1241
        Point2D.Double pt1 = new Point2D.Double(0.0, 0.0);
1242
        Point2D.Double pt2 = new Point2D.Double(0.0, 0.0);
1243
        Point2D.Double pt3 = new Point2D.Double(0.0, 0.0);
1244
        vp.mat.transform((Point2D) pts.get(0), pt0);
1245
        vp.mat.transform((Point2D) pts.get(1), pt1);
1246
        vp.mat.transform((Point2D) pts.get(2), pt2);
1247
        vp.mat.transform((Point2D) pts.get(3), pt3);
1248

    
1249
        // Aspa desde el extent
1250
        gp.moveTo((float) pt0.getX(), (float) pt0.getY());
1251
        gp.lineTo((float) pt2.getX(), (float) pt2.getY());
1252
        gp.moveTo((float) pt1.getX(), (float) pt1.getY());
1253
        gp.lineTo((float) pt3.getX(), (float) pt3.getY());
1254

    
1255
        // Extent
1256
        gp.moveTo((float) pt0.getX(), (float) pt0.getY());
1257
        gp.lineTo((float) pt1.getX(), (float) pt1.getY());
1258
        gp.lineTo((float) pt2.getX(), (float) pt2.getY());
1259
        gp.lineTo((float) pt3.getX(), (float) pt3.getY());
1260

    
1261
        if (extentOrig != extent) {
1262
            gp.lineTo((float) pt0.getX(), (float) pt0.getY());
1263

    
1264
            Vector pts = new Vector();
1265
            pts.add(proj.createPoint(extentOrig.minX(), extentOrig.minY()));
1266
            pts.add(proj.createPoint(extentOrig.maxX(), extentOrig.minY()));
1267
            pts.add(proj.createPoint(extentOrig.maxX(), extentOrig.maxY()));
1268
            pts.add(proj.createPoint(extentOrig.minX(), extentOrig.maxY()));
1269

    
1270
            vp.mat.transform((Point2D) pts.get(0), pt0);
1271
            vp.mat.transform((Point2D) pts.get(1), pt1);
1272
            vp.mat.transform((Point2D) pts.get(2), pt2);
1273
            vp.mat.transform((Point2D) pts.get(3), pt3);
1274
            gp.moveTo((float) pt0.getX(), (float) pt0.getY());
1275
            gp.lineTo((float) pt1.getX(), (float) pt1.getY());
1276
            gp.lineTo((float) pt2.getX(), (float) pt2.getY());
1277
            gp.lineTo((float) pt3.getX(), (float) pt3.getY());
1278
        }
1279

    
1280
        gp.closePath();
1281

    
1282
        return gp;
1283
    }
1284

    
1285
    public IProjection getProjection() {
1286
        return proj;
1287
    }
1288

    
1289
    public void setProjection(IProjection p) {
1290
        proj = p;
1291
    }
1292

    
1293
    public void reProject(ICoordTrans rp) {
1294
        this.rp = rp.getInverted();
1295
        System.out.println("PxRaster: reProject()");
1296

    
1297
        //geoFile.reProject(rp);
1298
        Vector savePts = pts;
1299

    
1300
        pts = new Vector();
1301
        extent = new Extent();
1302

    
1303
        Point2D ptDest = null;
1304

    
1305
        for (int i = 0; i < savePts.size(); i++) {
1306
            ptDest = rp.getPDest().createPoint(0.0, 0.0);
1307
            ptDest = rp.convert((Point2D) savePts.get(i), ptDest);
1308
            pts.add(ptDest);
1309
            extent.add(ptDest);
1310
        }
1311

    
1312
        setProjection(rp.getPDest());
1313
    }
1314

    
1315
    /**
1316
     * Obtiene el Stack Manager
1317
     * @return
1318
     */
1319
    public RasterFilterStackManager getStackManager() {
1320
        return this.stackManager;
1321
    }
1322

    
1323
    /**
1324
     * Asigna el Stack Manager
1325
     * @return
1326
     */
1327
    public void setStackManager(RasterFilterStackManager sm) {
1328
        this.stackManager = sm;
1329
    }
1330

    
1331
    /**
1332
     * Estructura que representa la relaci?n entre un fichero y la banda que se
1333
     * utiliza de este.
1334
     * @author Nacho Brodin <brodin_ign@gva.es>
1335
     */
1336
    class FileBands {
1337
        GeoRasterFile grf; //Fichero
1338
        int band; //Banda asinada
1339
        int filePos; //posici?n del fichero
1340

    
1341
        /**
1342
         * @return Returns the band.
1343
         */
1344
        public int getBand() {
1345
            return band;
1346
        }
1347

    
1348
        /**
1349
         * @param band The band to set.
1350
         */
1351
        public void setBand(int band) {
1352
            this.band = band;
1353
        }
1354

    
1355
        /**
1356
         * @return Returns the band.
1357
         */
1358
        public int getPos() {
1359
            return filePos;
1360
        }
1361

    
1362
        /**
1363
         * @param band The band to set.
1364
         */
1365
        public void setPos(int pos) {
1366
            this.filePos = pos;
1367
        }
1368

    
1369
        /**
1370
         * @return Returns the grf.
1371
         */
1372
        public GeoRasterFile getGeoRasterFile() {
1373
            return grf;
1374
        }
1375

    
1376
        /**
1377
         * @param grf The grf to set.
1378
         */
1379
        public void setGeoRasterFile(GeoRasterFile grf) {
1380
            this.grf = grf;
1381
        }
1382
    }
1383

    
1384
    /**
1385
     * Clase que lleva la gesti?n entre la relaci?n de ficheros representados
1386
     * por un GeoRasterFile y el n?mero de bandas que contienen. Esto es necesario
1387
     * para la actualizaci?n de la vista ya que para un Image dado podemos tener
1388
     * multiples bandas que pueden ser leidas desde diferentes ficheros.
1389
     *
1390
     * @author Nacho Brodin <brodin_ign@gva.es>
1391
     */
1392
    class BandSwitch {
1393
        private ArrayList geoFiles = new ArrayList(); //Lista de GeoRasterFile con los ficheros raster cargados
1394
        private FileBands[] listBands = new FileBands[3];
1395
        private boolean debug = false;
1396

    
1397
        BandSwitch() {
1398
            for (int i = 0; i < listBands.length; i++)
1399
                listBands[i] = new FileBands();
1400
        }
1401

    
1402
        /**
1403
         * A?ade un fichero
1404
         * @param grf
1405
         */
1406
        public void addFile(GeoRasterFile grf) {
1407
            geoFiles.add(grf);
1408

    
1409
            if (debug) {
1410
                this.show("addFile");
1411
            }
1412
        }
1413

    
1414
        /**
1415
         * Elimina un fichero
1416
         * @param grf
1417
         */
1418
        public void removeFile(GeoRasterFile grf) {
1419
            for (int iFile = 0; iFile < geoFiles.size(); iFile++) {
1420
                if (grf.equals(geoFiles.get(iFile))) {
1421
                    geoFiles.remove(iFile);
1422
                    iFile--;
1423
                }
1424
            }
1425

    
1426
            if (debug) {
1427
                this.show("removeFile");
1428
            }
1429
        }
1430

    
1431
        /**
1432
         *
1433
         * @param flag
1434
         * @param grf
1435
         * @param nBand
1436
         */
1437
        public void setBand(int flag, GeoRasterFile grf, int nBand) {
1438
            if ((flag & GeoRasterFile.RED_BAND) == GeoRasterFile.RED_BAND) {
1439
                listBands[0].setBand(nBand);
1440
                listBands[0].setGeoRasterFile(grf);
1441
            } else if ((flag & GeoRasterFile.GREEN_BAND) == GeoRasterFile.GREEN_BAND) {
1442
                listBands[1].setBand(nBand);
1443
                listBands[1].setGeoRasterFile(grf);
1444
            } else if ((flag & GeoRasterFile.BLUE_BAND) == GeoRasterFile.BLUE_BAND) {
1445
                listBands[2].setBand(nBand);
1446
                listBands[2].setGeoRasterFile(grf);
1447
            } else {
1448
                return;
1449
            }
1450

    
1451
            grf.setBand(flag, nBand);
1452
        }
1453

    
1454
        /**
1455
         * Asigna las bandas
1456
         * @param flag
1457
         * @param nBand
1458
         */
1459
        public void setBand(int flag, int nBand) {
1460
            int cont = 0;
1461

    
1462
            for (int iGrf = 0; iGrf < geoFiles.size(); iGrf++) {
1463
                for (int iBand = 0;
1464
                         iBand < ((GeoRasterFile) geoFiles.get(iGrf)).getBandCount();
1465
                         iBand++) {
1466
                    if (((flag & GeoRasterFile.RED_BAND) == GeoRasterFile.RED_BAND) &&
1467
                            (cont == nBand)) {
1468
                        listBands[0].setGeoRasterFile(((GeoRasterFile) geoFiles.get(iGrf)));
1469
                        listBands[0].setBand(iBand);
1470
                        listBands[0].setPos(iGrf);
1471
                        ((GeoRasterFile) geoFiles.get(iGrf)).setBand(flag, iBand);
1472

    
1473
                        //System.out.println("==>Asignando banda R FILE="+iGrf+" BANDA="+iBand);
1474
                    } else if (((flag & GeoRasterFile.GREEN_BAND) == GeoRasterFile.GREEN_BAND) &&
1475
                                   (cont == nBand)) {
1476
                        listBands[1].setGeoRasterFile(((GeoRasterFile) geoFiles.get(iGrf)));
1477
                        listBands[1].setBand(iBand);
1478
                        listBands[1].setPos(iGrf);
1479
                        ((GeoRasterFile) geoFiles.get(iGrf)).setBand(flag, iBand);
1480

    
1481
                        //System.out.println("==>Asignando banda G FILE="+iGrf+" BANDA="+iBand);
1482
                    } else if (((flag & GeoRasterFile.BLUE_BAND) == GeoRasterFile.BLUE_BAND) &&
1483
                                   (cont == nBand)) {
1484
                        listBands[2].setGeoRasterFile(((GeoRasterFile) geoFiles.get(iGrf)));
1485
                        listBands[2].setBand(iBand);
1486
                        listBands[2].setPos(iGrf);
1487
                        ((GeoRasterFile) geoFiles.get(iGrf)).setBand(flag, iBand);
1488

    
1489
                        //System.out.println("==>Asignando banda B FILE="+iGrf+" BANDA="+iBand);
1490
                    }
1491

    
1492
                    cont++;
1493
                }
1494
            }
1495

    
1496
            if (debug) {
1497
                this.show("setBand");
1498
            }
1499
        }
1500

    
1501
        /**
1502
         * Obtiene el n?mero de bandas
1503
         * @return
1504
         */
1505
        public int getBandCount() {
1506
            int nbandas = 0;
1507

    
1508
            for (int iGrf = 0; iGrf < geoFiles.size(); iGrf++)
1509
                nbandas += ((GeoRasterFile) geoFiles.get(iGrf)).getBandCount();
1510

    
1511
            return nbandas;
1512
        }
1513

    
1514
        /**
1515
         * Obtiene el GeoRasterFile que hay que leer para cargar la banda del rojo
1516
         * y la banda de este fichero que se utiliza para esta asignaci?n.
1517
         * @return        Estructura FileBand con la relaci?n fichero-banda
1518
         */
1519
        public FileBands getBandR() {
1520
            return listBands[0];
1521
        }
1522

    
1523
        /**
1524
         * Obtiene el GeoRasterFile que hay que leer para cargar la banda del verde
1525
         * y la banda de este fichero que se utiliza para esta asignaci?n.
1526
         * @return        Estructura FileBand con la relaci?n fichero-banda
1527
         */
1528
        public FileBands getBandG() {
1529
            return listBands[1];
1530
        }
1531

    
1532
        /**
1533
         * Obtiene el GeoRasterFile que hay que leer para cargar la banda del azul
1534
         * y la banda de este fichero que se utiliza para esta asignaci?n.
1535
         * @return        Estructura FileBand con la relaci?n fichero-banda
1536
         */
1537
        public FileBands getBandB() {
1538
            return listBands[2];
1539
        }
1540

    
1541
        public void show(String op) {
1542
            String banda = null;
1543
            System.out.println("** " + op + " **");
1544

    
1545
            for (int i = 0; i < 3; i++) {
1546
                if (i == 0) {
1547
                    banda = new String("Rojo");
1548
                } else if (i == 1) {
1549
                    banda = new String("Verde");
1550
                } else if (i == 2) {
1551
                    banda = new String("Azul");
1552
                }
1553

    
1554
                System.out.println("** BANDA IMAGE=" + banda + " FILEPOS=" +
1555
                                   listBands[i].getBand() +
1556
                                   " BANDA DEL FICHERO=" +
1557
                                   listBands[i].getBand());
1558
            }
1559
        }
1560
    }
1561
        /**
1562
         * @return Returns the vName.
1563
         */
1564
        public String getVName() {
1565
                return vName;
1566
        }
1567
        /**
1568
         * @param name The vName to set.
1569
         */
1570
        public void setVName(String name) {
1571
                vName = name;
1572
        }
1573

    
1574
        /**
1575
         * Obtiene el ?ltimo Image volcado en pantalla 
1576
         * @return
1577
         */
1578
        public Image getGeoImage() {
1579
                return geoImage;
1580
        }
1581

    
1582
        /**
1583
         * Obtiene el ?ltimo viewPort de la vista
1584
         * @return ViewPortData
1585
         */
1586
        public ViewPortData getLastViewPort() {
1587
                return lastViewPort;
1588
        }
1589
}