Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.io / org.gvsig.raster.io.base / src / main / java / org / gvsig / fmap / dal / coverage / dataset / io / ErmapperProvider.java @ 220

History | View | Annotate | Download (33.6 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.dataset.io;
23

    
24
import java.awt.geom.AffineTransform;
25
import java.awt.geom.NoninvertibleTransformException;
26
import java.awt.geom.Point2D;
27
import java.util.Vector;
28

    
29
import org.cresques.cts.ICoordTrans;
30
import org.gvsig.fmap.dal.DALFileLocator;
31
import org.gvsig.fmap.dal.DALLocator;
32
import org.gvsig.fmap.dal.DataStore;
33
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
34
import org.gvsig.fmap.dal.coverage.dataset.io.param.ErmapperStoreParameters;
35
import org.gvsig.fmap.dal.coverage.dataset.io.server.ErmapperFilesystemServerExplorer;
36
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
37
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
38
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
39
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
40
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
41
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
42
import org.gvsig.fmap.dal.coverage.exception.ParsingException;
43
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
44
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
45
import org.gvsig.fmap.dal.coverage.grid.render.TileListener;
46
import org.gvsig.fmap.dal.coverage.store.RasterFileStoreParameters;
47
import org.gvsig.fmap.dal.coverage.store.RasterStoreParameters;
48
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
49
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
50
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
51
import org.gvsig.metadata.MetadataLocator;
52
import org.gvsig.raster.impl.datastruct.ExtentImpl;
53
import org.gvsig.raster.impl.process.RasterTask;
54
import org.gvsig.raster.impl.process.RasterTaskQueue;
55
import org.gvsig.raster.impl.provider.DefaultRasterProvider;
56
import org.gvsig.raster.impl.provider.RasterProvider;
57
import org.gvsig.raster.impl.store.AbstractRasterDataStore;
58
import org.gvsig.raster.impl.store.AbstractRasterStoreParameters;
59
import org.gvsig.raster.impl.store.DefaultStoreFactory;
60
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
61
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
62
import org.gvsig.tools.ToolsLocator;
63
import org.gvsig.tools.extensionpoint.ExtensionPoint;
64
import org.gvsig.tools.extensionpoint.ExtensionPointManager;
65

    
66
import com.ermapper.ecw.JNCSException;
67
import com.ermapper.ecw.JNCSFile;
68
import com.ermapper.ecw.JNCSFileNotOpenException;
69
import com.ermapper.ecw.JNCSInvalidSetViewException;
70
import com.ermapper.ecw.JNCSProgressiveUpdate;
71
/**
72
 * Driver de Ecw
73
 *
74
 * @author Nacho Brodin (nachobrodin@gmail.com)
75
 */
76
public class ErmapperProvider extends DefaultRasterProvider implements JNCSProgressiveUpdate {
77
        public static String                  NAME                     = "Ermapper Store";
78
        public static String                  DESCRIPTION              = "Ermapper Raster file";
79
        public static final String            METADATA_DEFINITION_NAME = "ErmapperStore";
80
        private JNCSFile                                       file                     = null;
81
        protected Transparency                        fileTransparency         = null;
82
        private Extent                        viewRequest              = null;
83
        private DataStoreColorInterpretation  colorInterpr             = null;
84
        private boolean                       open                     = false;
85

    
86
        public static void register() {
87
                ExtensionPointManager extensionPoints = ToolsLocator.getExtensionPointManager();
88
                ExtensionPoint point = extensionPoints.get("RasterReader");
89
                point.append("ecw", "", ErmapperProvider.class);
90
                point.append("jp2", "", ErmapperProvider.class);
91
                
92
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
93
                if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
94
                        dataman.registerStoreProvider(NAME,
95
                                        ErmapperProvider.class, 
96
                                        ErmapperStoreParameters.class);
97
                }
98
                
99
                if(DALFileLocator.getFilesystemServerExplorerManager() != null)
100
                        DALFileLocator.getFilesystemServerExplorerManager().registerProvider(
101
                                        NAME, 
102
                                        DESCRIPTION,
103
                                        ErmapperFilesystemServerExplorer.class);
104
                
105
            dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
106
        }
107

    
108
        @SuppressWarnings("unchecked")
109
        class Contour extends Vector {
110
                final private static long serialVersionUID = 0;
111
                public double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE;
112
                public double maxX = -Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
113
                public Contour() {
114
                        super();
115
                }
116
                public void add(Point2D pt) {
117
                        super.add(pt);
118
                        if (pt.getX() > maxX) maxX = pt.getX();
119
                        if (pt.getX() < minX) minX = pt.getX();
120
                        if (pt.getY() > maxY) maxY = pt.getY();
121
                        if (pt.getY() < minY) minY = pt.getY();
122
                }
123
        }
124
        
125
        /**
126
         * Constructor. Abre el dataset.
127
         * @param proj Proyecci?n
128
         * @param fName Nombre del fichero ecw
129
         * @throws NotSupportedExtensionException
130
         */
131
        public ErmapperProvider(String params) throws NotSupportedExtensionException {
132
                super(params);
133
                if(params instanceof String) {
134
                        ErmapperStoreParameters p = new ErmapperStoreParameters();
135
                        p.setURI((String)params);
136
                        super.init(p, null, ToolsLocator.getDynObjectManager()
137
                                        .createDynObject(
138
                                                        MetadataLocator.getMetadataManager().getDefinition(
139
                                                                        DataStore.METADATA_DEFINITION_NAME)));
140
                        init(p, null);
141
                }
142
        }
143
        
144
        public ErmapperProvider(ErmapperStoreParameters params,
145
                        AbstractRasterDataStore storeServices) throws NotSupportedExtensionException {
146
                super(params, storeServices, ToolsLocator.getDynObjectManager()
147
                                .createDynObject(
148
                                                MetadataLocator.getMetadataManager().getDefinition(
149
                                                                DataStore.METADATA_DEFINITION_NAME)));
150
                init(params, storeServices);
151
        }
152

    
153
        /**
154
         * Abre el dataset.
155
         * @param proj Proyecci?n
156
         * @param fName Nombre del fichero ecw
157
         * @throws NotSupportedExtensionException
158
         */
159
        public void init (AbstractRasterStoreParameters params,
160
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
161
                setParam(params);
162
                if (!((RasterFileStoreParameters)param).getFile().exists() && !((RasterStoreParameters)param).getURI().startsWith("ecwp:"))
163
                        throw new NotSupportedExtensionException("Extension not supported");
164

    
165
                try {
166
                        file = new JNCSFile(((RasterStoreParameters)param).getURI(), false);
167
                } catch (JNCSException e1) {
168
                        throw new NotSupportedExtensionException("Error loading the ecw file", e1);
169
                }
170
                load();
171
                bandCount = file.numBands;
172
                getTransparency();
173

    
174
                int[] dt = new int[bandCount];
175
                for (int i = 0; i < bandCount; i++)
176
                        dt[i] = Buffer.TYPE_BYTE;
177
                setDataType(dt);
178

    
179
                super.init();
180

    
181
                try {
182
                        loadFromRmf(getRmfBlocksManager());
183
                } catch (ParsingException e) {
184
                        //No lee desde rmf
185
                }
186
                open = true;
187
        }
188

    
189
        /**
190
         * Carga un ECW.
191
         * @param fname
192
         */
193
        public RasterProvider load() {
194
                ownTransformation = new AffineTransform(file.cellIncrementX, 0, 0, file.cellIncrementY, file.originX, file.originY);
195
                externalTransformation = (AffineTransform) ownTransformation.clone();
196
                return this;
197
        }
198
        
199
        /*
200
         * (non-Javadoc)
201
         * @see org.gvsig.raster.impl.provider.RasterProvider#isOpen()
202
         */
203
        public boolean isOpen() {
204
                return open;
205
        }
206

    
207
        /**
208
         * Cierra el fichero ECW
209
         */
210
        public void close() {
211
                if(file != null) {
212
                        open = false;
213
                        file.close(false);
214
                        file = null;
215
                }
216
        }
217

    
218
        /**
219
         * Obtiene el objeto que contiene el estado de la transparencia
220
         */
221
        public Transparency getTransparency() {
222
                if(fileTransparency == null)
223
                        fileTransparency = new DataStoreTransparency();
224
                return fileTransparency;
225
        }
226

    
227
        /**
228
         * Devuelve el ancho de la imagen
229
         */
230
        public double getWidth() {
231
                return file.width;
232
        }
233

    
234
        /**
235
         * Devuelve el alto de la imagen
236
         */
237
        public double getHeight() {
238
                return file.height;
239
        }
240

    
241
        /**
242
         * Obtiene el extent de la ?ltima ventana seleccionada.
243
         * @return Extent
244
         */
245
        public Extent getView() {
246
                return viewRequest;
247
        }
248

    
249
        /*
250
         * (non-Javadoc)
251
         * @see org.gvsig.fmap.driver.RasterDataset#setView(org.gvsig.fmap.raster.Extent)
252
         */
253
        public void setView(Extent e) {
254
                viewRequest = new ExtentImpl(e);
255
        }
256

    
257
        /**
258
         * Cuando se hace una petici?n de carga de buffer la extensi?n pedida puede estar ajustada a la extensi?n del raster
259
         * o no estarlo. En caso de no estarlo los pixeles del buffer que caen fuera de la extensi?n del raster tendr?n valor
260
         * de NoData. Esta funci?n calcula en que pixel del buffer hay que empezar a escribir en caso de que este sea mayor
261
         * que los datos a leer.
262
         * @param dWorldTLX Posici?n X superior izquierda en coord reales
263
         * @param dWorldTLY Posici?n Y superior izquierda en coord reales
264
         * @param dWorldBRX Posici?n X inferior derecha en coord reales
265
         * @param dWorldBRY Posici?n Y inferior derecha en coord reales
266
         * @param nWidth Ancho en pixeles del buffer
267
         * @param nHeight Alto en pixeles del buffer
268
         * @return desplazamiento dentro del buffer en X e Y
269
         */
270
        /*private int[] calcStepBuffer(Extent dataExtent, int nWidth, int nHeight, int[] stpBuffer) {
271
                Extent imageExtent = getExtentWithoutRot();
272
                Extent ajustDataExtent = RasterUtilities.calculateAdjustedView(dataExtent, imageExtent);
273
                if(!RasterUtilities.compareExtents(dataExtent, ajustDataExtent)) {
274
                        Point2D p1 = worldToRaster(new Point2D.Double(ajustDataExtent.minX(), ajustDataExtent.maxY()));
275
                        Point2D p2 = worldToRaster(new Point2D.Double(ajustDataExtent.maxX(), ajustDataExtent.minY()));
276
                        Point2D p3 = worldToRaster(new Point2D.Double(dataExtent.minX(), dataExtent.maxY()));
277
                        Point2D p4 = worldToRaster(new Point2D.Double(dataExtent.maxX(), dataExtent.minY()));
278
                        //Ese es el ancho y alto q tendr?a el buffer en caso de haberse ajustado
279
                        int w = (int)Math.abs(Math.ceil(p2.getX()) - Math.floor(p1.getX()));
280
                        int h = (int)Math.abs(Math.floor(p1.getY()) - Math.ceil(p2.getY()));
281

282
                        stpBuffer[0] = (int)(p1.getX() + (-p3.getX()));
283
                        stpBuffer[1] = (int)(p1.getY() + (-p3.getY()));
284
                        stpBuffer[2] = stpBuffer[0] + w;
285
                        stpBuffer[3] = stpBuffer[1] + h;
286
                        return new int[]{w, h};
287
                }
288
                return new int[]{nWidth, nHeight};
289
        }*/
290
        
291
        /*
292
         * (non-Javadoc)
293
         * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#getWindowRaster(double, double, double, double, int, int, org.gvsig.fmap.dal.coverage.datastruct.BandList, org.gvsig.fmap.dal.coverage.dataset.Buffer, org.gvsig.fmap.dal.coverage.grid.render.TileListener, int)
294
         */
295
        public void getWindowRaster(double minX, double minY, double maxX, double maxY, 
296
                         int bufWidth, int bufHeight, BandList bandList, TileListener listener, int frameInPx)throws ProcessInterruptedException, RasterDriverException {
297
                 
298
        }
299

    
300
        /*
301
         * (non-Javadoc)
302
         * @see org.gvsig.raster.dataset.RasterDataset#getWindowRaster(double, double, double, double, org.gvsig.raster.dataset.BandList, org.gvsig.raster.dataset.IBuffer)
303
         */
304
        public Buffer getWindowRaster(double ulx, double uly, double lrx, double lry, 
305
                        BandList bandList, Buffer rasterBuf) throws ProcessInterruptedException, RasterDriverException {
306
                Point2D p1 = new Point2D.Double(ulx, uly);
307
                Point2D p2 = new Point2D.Double(lrx, lry);
308
                try {
309
                        externalTransformation.inverseTransform(p1, p1);
310
                        externalTransformation.inverseTransform(p2, p2);
311
                        ownTransformation.transform(p1, p1);
312
                        ownTransformation.transform(p2, p2);
313
                } catch (NoninvertibleTransformException e) {
314
                        throw new RasterDriverException("Noninvertible transform");
315
                }
316

    
317
                Extent selectedExtent = new ExtentImpl(p1.getX(), p1.getY(), p2.getX(), p2.getY());
318

    
319
                setView(selectedExtent);
320
                int wPx = rasterBuf.getWidth();
321
                int hPx = rasterBuf.getHeight();
322
                int[] stpBuffer = new int[]{0, 0 , wPx, hPx};
323

    
324
                loadBuffer(viewRequest, wPx, hPx, rasterBuf, bandList, stpBuffer);
325

    
326
                return rasterBuf;
327
        }
328

    
329
        /*
330
         * (non-Javadoc)
331
         * @see org.gvsig.fmap.driver.RasterDataset#getWindowRaster(double, double, double, double, org.gvsig.fmap.driver.BandList, org.gvsig.fmap.driver.Buffer, boolean)
332
         */
333
        public Buffer getWindowRaster(double ulx, double uly, double w, double h, 
334
                        BandList bandList, Buffer rasterBuf, boolean adjustToExtent) throws ProcessInterruptedException, RasterDriverException {
335
                //El incremento o decremento de las X e Y depende de los signos de rotaci?n y escala en la matriz de transformaci?n. Por esto
336
                //tenemos que averiguar si lrx es x + w o x -w, asi como si lry es y + h o y - h
337
                Extent ext = getExtent();
338
                Point2D pInit = rasterToWorld(new Point2D.Double(0, 0));
339
                Point2D pEnd = rasterToWorld(new Point2D.Double(getWidth(), getHeight()));
340
                double wRaster = Math.abs(pEnd.getX() - pInit.getX());
341
                double hRaster = Math.abs(pEnd.getY() - pInit.getY());
342
                double lrx = (((ext.getULX() - wRaster) > ext.maxX()) || ((ext.getULX() - wRaster) < ext.minX())) ? (ulx + w) : (ulx - w);
343
                double lry = (((ext.getULY() - hRaster) > ext.maxY()) || ((ext.getULY() - hRaster) < ext.minY())) ? (uly + h) : (uly - h);
344

    
345
                Point2D p1 = new Point2D.Double(ulx, uly);
346
                Point2D p2 = new Point2D.Double(lrx, lry);
347
                try {
348
                        externalTransformation.inverseTransform(p1, p1);
349
                        externalTransformation.inverseTransform(p2, p2);
350
                        ownTransformation.transform(p1, p1);
351
                        ownTransformation.transform(p2, p2);
352
                } catch (NoninvertibleTransformException e) {
353
                        throw new RasterDriverException("Noninvertible transform");
354
                }
355

    
356
                Extent selectedExtent = new ExtentImpl(p1.getX(), p1.getY(), p2.getX(), p2.getY());
357

    
358
                setView(selectedExtent);
359
                int wPx = rasterBuf.getWidth();
360
                int hPx = rasterBuf.getHeight();
361
                int[] stpBuffer = new int[]{0, 0 , wPx, hPx};
362

    
363
                //TODO: FUNCIONALIDAD: Implementar adjustToExtent = false
364
                /*if(!adjustToExtent){
365
                                         int[] wh = calcStepBuffer(selectedExtent, wPx, hPx, stpBuffer);
366
                                         if(x < 0)
367
                                                 x  = 0;
368
                                         if(y < 0)
369
                                                 y  = 0;
370
                                         readData(buf, bandList, x, y, wh[0], wh[1], wh[0], wh[1], 0, 0, stpBuffer);
371
                                         return;
372
                        }*/
373

    
374
                loadBuffer(viewRequest, wPx, hPx, rasterBuf, bandList, stpBuffer);
375

    
376
                return rasterBuf;
377
        }
378

    
379
        /*
380
         * (non-Javadoc)
381
         * @see org.gvsig.fmap.driver.RasterDataset#getWindowRaster(int, int, int, int, org.gvsig.fmap.driver.BandList, org.gvsig.fmap.driver.Buffer)
382
         */
383
        public Buffer getWindowRaster(int x, int y, int w, int h, 
384
                        BandList bandList, Buffer rasterBuf) throws ProcessInterruptedException, RasterDriverException {
385
                Point2D init = this.rasterToWorld(new Point2D.Double(x, y));
386
                Point2D end = this.rasterToWorld(new Point2D.Double(x + w, y + h));
387
                Extent selectedExtent = new ExtentImpl(init.getX(), init.getY(), end.getX(), end.getY());
388
                setView(selectedExtent);
389
                int[] stpBuffer = new int[]{0, 0 , w, h};
390

    
391
                loadBuffer(viewRequest, w, h, rasterBuf, bandList, stpBuffer);
392
                return rasterBuf;
393
        }
394

    
395
        /*
396
         * (non-Javadoc)
397
         * @see org.gvsig.fmap.driver.RasterDataset#getWindowRaster(double, double, double, double, int, int, org.gvsig.fmap.driver.BandList, org.gvsig.fmap.driver.Buffer, boolean)
398
         */
399
        public Buffer getWindowRaster(double ulx, double uly, double lrx, double lry, 
400
                        int bufWidth, int bufHeight, BandList bandList, Buffer rasterBuf, boolean adjustToExtent) throws ProcessInterruptedException, RasterDriverException {
401
                Point2D p1 = new Point2D.Double(ulx, uly);
402
                Point2D p2 = new Point2D.Double(lrx, lry);
403
                try {
404
                        externalTransformation.inverseTransform(p1, p1);
405
                        externalTransformation.inverseTransform(p2, p2);
406
                        ownTransformation.transform(p1, p1);
407
                        ownTransformation.transform(p2, p2);
408
                } catch (NoninvertibleTransformException e) {
409
                        throw new RasterDriverException("Noninvertible transform");
410
                }
411
                Extent selectedExtent = new ExtentImpl(p1, p2);
412
                setView(selectedExtent);
413
                int[] stpBuffer = new int[]{0, 0 , bufWidth, bufHeight};
414

    
415
                //TODO: FUNCIONALIDAD: Implementar adjustToExtent = false
416

    
417
                loadBuffer(viewRequest, bufWidth, bufHeight, rasterBuf, bandList, stpBuffer);
418
                return rasterBuf;
419
        }
420

    
421
        /*
422
         * (non-Javadoc)
423
         * @see org.gvsig.fmap.driver.RasterDataset#getWindowRaster(int, int, int, int, int, int, org.gvsig.fmap.driver.BandList, org.gvsig.fmap.driver.Buffer)
424
         */
425
        public Buffer getWindowRaster(int x, int y, int w, int h, 
426
                        int bufWidth, int bufHeight, BandList bandList, Buffer rasterBuf) throws ProcessInterruptedException, RasterDriverException {
427
                Point2D init = this.rasterToWorld(new Point2D.Double(x, y));
428
                Point2D end = this.rasterToWorld(new Point2D.Double(x + w, y + h));
429
                Extent selectedExtent = new ExtentImpl(init.getX(), init.getY(), end.getX(), end.getY());
430
                setView(selectedExtent);
431
                int[] stpBuffer = new int[]{0, 0 , bufWidth, bufHeight};
432

    
433
                loadBuffer(viewRequest, bufWidth, bufHeight, rasterBuf, bandList, stpBuffer);
434
                return rasterBuf;
435
        }
436

    
437
        /**
438
         * Carga el buffer con las bandas RGB del raster con los par?metros especificados de extensi?n
439
         * y tama?o de buffer. El problema de ecw es que solo podemos leer 3 bandas de una vez ya que solo disponemos
440
         * de una llamada readLineRGBA. Para leer m?s bandas tendremos que hacer multiples llamadas a setView para leer
441
         * 3 cada vez.
442
         *
443
         * Si por ejemplo tenemos un ecw de 6 bandas [0, 1, 2, 3, 4, 5] y queremos cargar un buffer con el siguiente orden
444
         * [0, -, 2, -, 4, -] La variable readBandsFromECW har? la llamada a setView con los valores [0, 2, 4, 0, 0, 0]. La
445
         * funci?n drawRGB ser? la encargada de hacer el switch para obtener [0, -, 2, -, 4, -].
446
         *
447
         * Bug#1: Si se dispone de un ecw de m?s de tres bandas podemos llamar a setView con readBandsFromECW con el orden
448
         * que queramos, por ejemplo [3, 2, 5, 1, 0] pero para ecw de 3 bandas la llamada con las bandas cambiadas no
449
         * hace caso. El caso de readBandsFromECW = [2, 0, 1] ser? tomado siempre como [0, 1, 2].
450
         *
451
         * @param selectedExtent Extensi?n seleccionada
452
         * @param bufWidth Ancho de buffer
453
         * @param bufHeight Alto de buffer
454
         * @param rasterBuf Buffer de datos
455
         */
456
        private void loadBuffer(Extent selectedExtent, int bufWidth, int bufHeight, Buffer rasterBuf, BandList bandList, int[] stpBuffer) throws ProcessInterruptedException, RasterDriverException {
457
                try{
458
                        RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
459

    
460
                        //Leemos el raster desde la librer?a
461

    
462
                        //Extent ext = getExtent();//new Extent(file.originX, file.originY, file.originX + (file.width * file.cellIncrementX), file.originY + (file.height * file.cellIncrementY));
463
                        //selectedExtent = RasterUtilities.calculateAdjustedView(selectedExtent, ext);
464
                        //selectedExtent = RasterUtilities.calculateAdjustedView(selectedExtent, this.getAffineTransform(), new Dimension(file.width, file.height));
465
                        int[] readBandsFromECW = new int[Math.max(file.numBands, 3)];
466
                        int[] readBands = new int[Math.max(file.numBands, 3)];
467

    
468

    
469
                        for(int i = 0; i < readBandsFromECW.length; i ++)
470
                                readBands[i] = -1;
471
                        int cont = 0;
472
                        for(int i = 0; i < file.numBands; i++) {
473
                                int[] bandsToDraw = bandList.getBand(i).getBufferBandListToDraw();
474
                                if(bandsToDraw != null) {
475
                                        for(int j = 0; j < bandsToDraw.length; j++){
476
                                                readBandsFromECW[cont] = i;
477
                                                readBands[cont] = i;
478
                                                cont ++;
479
                                        }
480
                                }
481

    
482
                        }
483

    
484
                        if(task.getEvent() != null)
485
                                task.manageEvent(task.getEvent());
486

    
487
                        //Si el ancho y alto pedido no coincide con el estimado es que se intenta resamplear.
488
                        //Otros drivers soportan el resampleo pero no es el caso. Hay que hacer la petici?n y luego remuestrear.
489

    
490
                        /*if((selectedExtent.width()/file.cellIncrementX) || (selectedExtent.height()/file.cellIncrementY)) {
491

492
                        }*/
493

    
494
                        if(bufWidth > Math.round(Math.abs(selectedExtent.width()/file.cellIncrementX)))
495
                                bufWidth = (int)Math.round(Math.abs(selectedExtent.width()/file.cellIncrementX));
496
                        if(bufHeight > Math.round(Math.abs(selectedExtent.height()/file.cellIncrementY)))
497
                                bufHeight = (int)Math.round(Math.abs(selectedExtent.height()/file.cellIncrementY));
498
                        file.setView(file.numBands, readBandsFromECW, selectedExtent.minX(), selectedExtent.maxY(), selectedExtent.maxX(), selectedExtent.minY(), bufWidth, bufHeight);
499
                        
500
                        //Escribimos el raster sobre un Buffer
501
                        int[] pRGBArray = new int[bufWidth];
502
                        drawRGB(rasterBuf, pRGBArray, readBandsFromECW, bandList, task);
503

    
504
                }catch(JNCSInvalidSetViewException exc){
505
                        throw new RasterDriverException("Error setting coords");
506
                }catch (JNCSFileNotOpenException e) {
507
                        throw new RasterDriverException("Error opening file");
508
                }catch (JNCSException ex) {
509
                        throw new RasterDriverException("Error reading data");
510
                }
511

    
512
        }
513

    
514

    
515
        private void drawRGB(Buffer rasterBuf, int[] pRGBArray, int[] readBands, BandList bandList, RasterTask task) throws JNCSException, ProcessInterruptedException {
516
                int bandR = readBands[0];
517
                int bandG = (readBands.length > 1) ? readBands[1] : -1;
518
                int bandB = (readBands.length > 2) ? readBands[2] : -1;
519

    
520
                //********* caso especial que resuelve Bug#1 **********************
521
                if(file.numBands == 3 && bandList.getDrawableBandsCount() < 3) {
522
                        for(int i = 0; i < 3; i ++) {
523
                                int[] b = bandList.getBand(i).getBufferBandListToDraw();
524
                                if(b != null){
525
                                        bandG = 1; bandR = 0; bandB = 2;
526
                                }
527
                        }
528
                }
529
                if(file.numBands == 3 && bandR == bandG && bandG == bandB) { //caso especial que resuelve Bug#1
530
                        for(int i = 0; i < 3; i ++) {
531
                                int[] b = bandList.getBand(i).getBufferBandListToDraw();
532
                                if(b != null) {
533
                                        if(i == 0) {
534
                                                for (int line = 0; line < rasterBuf.getHeight(); line++) {
535
                                                        try {
536
                                                                file.readLineRGBA(pRGBArray);
537
                                                                for(int col = 0; col < pRGBArray.length; col ++){
538
                                                                        rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
539
                                                                        rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
540
                                                                        rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
541
                                                                }
542
                                                        } catch (JNCSException exc) {
543
                                                        }
544
                                                }
545
                                                return;
546
                                        }
547
                                        if(i == 1) {
548
                                                for (int line = 0; line < rasterBuf.getHeight(); line++) {
549
                                                        try {
550
                                                                file.readLineRGBA(pRGBArray);
551
                                                                for(int col = 0; col < pRGBArray.length; col ++){
552
                                                                        rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
553
                                                                        rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
554
                                                                        rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
555
                                                                }
556
                                                        } catch (JNCSException exc) {
557
                                                        }
558
                                                }
559
                                                return;
560
                                        }
561
                                        if(i == 2) {
562
                                                for (int line = 0; line < rasterBuf.getHeight(); line++) {
563
                                                        try {
564
                                                                file.readLineRGBA(pRGBArray);
565
                                                                for(int col = 0; col < pRGBArray.length; col ++){
566
                                                                        rasterBuf.setElem(line, col, bandR, (byte)(pRGBArray[col] & 0x000000ff));
567
                                                                        rasterBuf.setElem(line, col, bandG, (byte)(pRGBArray[col] & 0x000000ff));
568
                                                                        rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
569
                                                                }
570
                                                        } catch (JNCSException exc) {
571
                                                        }
572
                                                }
573
                                                return;
574
                                        }
575
                                }
576
                                if(task.getEvent() != null)
577
                                        task.manageEvent(task.getEvent());
578
                        }
579

    
580
                }
581
                //********* END caso especial que resuelve Bug#1 **********************
582

    
583
                if(bandR >= 0 && bandG >= 0 && bandB >= 0) {
584
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
585
                                try {
586
                                        file.readLineRGBA(pRGBArray);
587
                                        for(int col = 0; col < pRGBArray.length; col ++){
588
                                                rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
589
                                                rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
590
                                                rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
591
                                        }
592
                                } catch (JNCSException exc) {
593
                                }
594
                        }
595
                        return;
596
                }
597

    
598
                if(task.getEvent() != null)
599
                        task.manageEvent(task.getEvent());
600

    
601
                if(bandR >= 0 && bandG >= 0) {
602
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
603
                                try {
604
                                        file.readLineRGBA(pRGBArray);
605
                                        for(int col = 0; col < pRGBArray.length; col ++){
606
                                                rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
607
                                                rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
608
                                        }
609
                                } catch (JNCSException exc) {
610
                                }
611
                        }
612
                        return;
613
                }
614

    
615
                if(task.getEvent() != null)
616
                        task.manageEvent(task.getEvent());
617

    
618
                if(bandR >= 0){
619
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
620
                                try {
621
                                        file.readLineRGBA(pRGBArray);
622
                                        for(int col = 0; col < pRGBArray.length; col ++)
623
                                                rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
624
                                } catch (JNCSException exc) {
625
                                }
626
                        }
627
                        return;
628
                }
629

    
630
                if(task.getEvent() != null)
631
                        task.manageEvent(task.getEvent());
632

    
633
        }
634

    
635
        public void reProject(ICoordTrans rp) {
636
        }
637

    
638
        /*
639
         * (non-Javadoc)
640
         * @see org.gvsig.raster.dataset.RasterDataset#getBlockSize()
641
         */
642
        public int getBlockSize() {
643
                return 0;
644
        }
645

    
646
        /*
647
         * (non-Javadoc)
648
         * @see org.gvsig.raster.driver.RasterDataset#readCompletetLine(int, int)
649
         */
650
        public Object readCompleteLine(int line, int band) throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
651
                if(line < 0 || line >= file.height || band < 0 || band >= getBandCount())
652
                        throw new InvalidSetViewException("Request out of grid");
653

    
654
                Point2D begin = rasterToWorld(new Point2D.Double(0, line));
655
                Point2D end = rasterToWorld(new Point2D.Double(file.width, line + 1));
656
                int[] readBandsFromECW = new int[file.numBands];
657
                if(file.numBands <= 3) {
658
                        for(int i = 0; i < file.numBands; i++)
659
                                readBandsFromECW[i] = i;
660
                }else {
661
                        readBandsFromECW[0] = band;
662
                }
663

    
664
                Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
665

    
666
                try {
667
                        int[] value = new int[file.width];
668
                        file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, 1);
669
                        file.readLineRGBA(value);
670

    
671
                        if(file.numBands <= 3) {
672
                                switch(getDataType()[0]) {
673
                                case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
674
                                                                                switch(band) {
675
                                                                                case 0: for(int i = 0; i < file.width; i ++)
676
                                                                                                        b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
677
                                                                                                break;
678
                                                                                case 1: for(int i = 0; i < file.width; i ++)
679
                                                                                                        b[i] = (byte)(((value[i] & 0x0000ff00) >> 8) & 0xff);
680
                                                                                                break;
681
                                                                                case 2: for(int i = 0; i < file.width; i ++)
682
                                                                                                        b[i] = (byte)((value[i] & 0x000000ff) & 0xff);
683
                                                                                                break;
684
                                                                                }
685
                                                                                return b;
686
                                }
687
                        }else {
688
                                switch(getDataType()[0]) {
689
                                case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
690
                                                                                for(int i = 0; i < file.width; i ++)
691
                                                                                        b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
692
                                                                                break;
693
                                }
694
                        }
695
                        //TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
696
                } catch (JNCSFileNotOpenException e1) {
697
                        throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
698
                } catch (JNCSInvalidSetViewException e1) {
699
                        throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
700
                } catch (JNCSException e1) {
701
                        throw new RasterDriverException("Error la lectura de datos ecw");
702
                }
703

    
704
                return null;
705
        }
706

    
707
        /*
708
         * (non-Javadoc)
709
         * @see org.gvsig.raster.impl.provider.DefaultRasterProvider#readBlock(int, int)
710
         */
711
        public Object readBlock(int pos, int blockHeight) throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
712
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
713
                if(pos < 0)
714
                        throw new InvalidSetViewException("Request out of grid");
715

    
716
                if((pos + blockHeight) > file.height)
717
                        blockHeight = Math.abs(file.height - pos);
718

    
719
                Point2D begin = rasterToWorld(new Point2D.Double(0, pos));
720
                Point2D end = rasterToWorld(new Point2D.Double(file.width, pos + blockHeight));
721
                int[] readBandsFromECW = new int[file.numBands];
722

    
723
                for(int i = 0; i < file.numBands; i++)
724
                        readBandsFromECW[i] = i;
725

    
726
                byte[][][] buf = new byte[file.numBands][blockHeight][file.width];
727
                Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
728
                e = rasterUtil.calculateAdjustedView(getExtent(), e);
729

    
730
                try {
731
                        int[] value = new int[file.width];
732
                        file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, blockHeight);
733

    
734
                        if(file.numBands <= 3) {
735
                                for (int row = 0; row < blockHeight; row++) {
736
                                        file.readLineRGBA(value);
737
                                        switch(getDataType()[0]) {
738
                                        case Buffer.TYPE_BYTE:
739
                                                for(int col = 0; col < file.width; col ++) {
740
                                                        buf[0][row][col] = (byte)(((value[col] & 0x00ff0000) >> 16) & 0xff);
741
                                                        buf[1][row][col] = (byte)(((value[col] & 0x0000ff00) >> 8) & 0xff);
742
                                                        buf[2][row][col] = (byte)((value[col] & 0x000000ff) & 0xff);
743
                                                }
744
                                                break;
745
                                        }
746
                                }
747

    
748
                                if(task.getEvent() != null)
749
                                        task.manageEvent(task.getEvent());
750

    
751
                        } else {
752
                                //TODO: FUNCIONALIDAD: file.numBands > 3
753
                        }
754

    
755
                        //TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
756
                } catch (JNCSFileNotOpenException e1) {
757
                        throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
758
                } catch (JNCSInvalidSetViewException e1) {
759
                        throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
760
                } catch (JNCSException e1) {
761
                        throw new RasterDriverException("Error la lectura de datos ecw");
762
                }
763

    
764
                return buf;
765
        }
766

    
767
        /*
768
         * (non-Javadoc)
769
         * @see org.gvsig.raster.driver.RasterDataset#getData(int, int, int)
770
         */
771
        public Object getData(int x, int y, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
772
                if(x < 0 || y < 0 || x >= file.width || y >= file.height)
773
                        throw new InvalidSetViewException("Request out of grid");
774

    
775
                Point2D begin = new Point2D.Double(x, y);
776
                Point2D end = new Point2D.Double(x + 1, y + 1);
777

    
778
                ownTransformation.transform(begin, begin);
779
                ownTransformation.transform(end, end);
780

    
781
                int[] readBandsFromECW = new int[file.numBands];
782
                if(file.numBands <= 3){
783
                        for(int i = 0; i < file.numBands; i++)
784
                                readBandsFromECW[i] = i;
785
                }else{
786
                        readBandsFromECW[0] = band;
787
                }
788

    
789
                Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
790
                try {
791
                        int[] value = new int[1];
792
                        file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), 1, 1);
793
                        file.readLineRGBA(value);
794
                        if(file.numBands <= 3){
795
                                switch(band){
796
                                case 0: return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
797
                                case 1: return new Integer((((value[0] & 0x0000ff00) >> 8) & 0xffffffff));
798
                                case 2: return new Integer((((value[0] & 0x000000ff)) & 0xffffffff));
799
                                }
800
                        }
801
                        return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
802
                } catch (JNCSFileNotOpenException e1) {
803
                        throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
804
                } catch (JNCSInvalidSetViewException e1) {
805
                        throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
806
                } catch (JNCSException e1) {
807
                        throw new RasterDriverException("Error reading ecw data");
808
                }
809
        }
810

    
811
        public void refreshUpdate(int arg0, int arg1, double arg2, double arg3, double arg4, double arg5) {
812
        }
813

    
814
        public void refreshUpdate(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
815
        }
816

    
817
        /**
818
         * Obtiene el objeto que contiene que contiene la interpretaci?n de
819
         * color por banda
820
         * @return
821
         */
822
        public DataStoreColorInterpretation getColorInterpretation(){
823
                if(colorInterpr == null) {
824
                        colorInterpr = new DataStoreColorInterpretation();
825
                        colorInterpr.initColorInterpretation(getBandCount());
826
                        if(getBandCount() == 1)
827
                                colorInterpr.setColorInterpValue(0, DataStoreColorInterpretation.GRAY_BAND);
828
                        if(getBandCount() >= 3) {
829
                                colorInterpr.setColorInterpValue(0, DataStoreColorInterpretation.RED_BAND);
830
                                colorInterpr.setColorInterpValue(1, DataStoreColorInterpretation.GREEN_BAND);
831
                                colorInterpr.setColorInterpValue(2, DataStoreColorInterpretation.BLUE_BAND);
832
                        }
833
                }
834
                return colorInterpr;
835
        }
836

    
837
        /**
838
         * Asigna el objeto que contiene que contiene la interpretaci?n de
839
         * color por banda
840
         * @param DataStoreColorInterpretation
841
         */
842
        public void setColorInterpretation(DataStoreColorInterpretation colorInterpretation){
843
                this.colorInterpretation = colorInterpretation;
844
        }
845

    
846
        /*
847
         * (non-Javadoc)
848
         * @see org.gvsig.raster.dataset.RasterDataset#getOverviewCount(int)
849
         */
850
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
851
                if(band >= getBandCount())
852
                        throw new BandAccessException("Wrong band");
853
                return 0;
854
        }
855

    
856
        /*
857
         * (non-Javadoc)
858
         * @see org.gvsig.raster.dataset.RasterDataset#getOverviewWidth(int, int)
859
         */
860
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
861
                if (band >= getBandCount())
862
                        throw new BandAccessException("Wrong band");
863
                return 0;
864
        }
865

    
866
        /*
867
         * (non-Javadoc)
868
         * @see org.gvsig.raster.dataset.RasterDataset#getOverviewWidth(int, int)
869
         */
870
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
871
                if (band >= getBandCount())
872
                        throw new BandAccessException("Wrong band");
873
                return 0;
874
        }
875

    
876
        /*
877
         * (non-Javadoc)
878
         * @see org.gvsig.raster.dataset.RasterDataset#overviewsSupport()
879
         */
880
        public boolean overviewsSupport() {
881
                return false;
882
        }
883

    
884
        /*
885
         * (non-Javadoc)
886
         * @see org.gvsig.raster.driver.GeoData#getStringProjection()
887
         */
888
        public String getStringProjection() throws RasterDriverException{
889
                return file.projection;
890
        }
891

    
892
        /*
893
         * (non-Javadoc)
894
         * @see org.gvsig.raster.driver.GeoData#getStringProjection()
895
         */
896
        public String getWktProjection() {
897
                //System.err.println("======>" + file.projection);
898
                return null;
899
        }
900
        
901
        /*
902
         * (non-Javadoc)
903
         * @see org.gvsig.fmap.dal.raster.spi.CoverageStoreProvider#getName()
904
         */
905
        public String getName() {
906
                return NAME;
907
        }
908
        
909
        /*
910
         * (non-Javadoc)
911
         * @see org.gvsig.raster.impl.provider.RasterProvider#setStatus(org.gvsig.raster.impl.provider.RasterProvider)
912
         */
913
        public void setStatus(RasterProvider provider) {
914
                if(provider instanceof ErmapperProvider) {
915
                        //Not implemented yet
916
                }
917
        }
918
}