Statistics
| Revision:

gvsig-raster / org.gvsig.raster.ermapper / trunk / org.gvsig.raster.ermapper / org.gvsig.raster.ermapper.io / src / main / java / org / gvsig / raster / ermapper / io / ErmapperProvider.java @ 2449

History | View | Annotate | Download (27.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.raster.ermapper.io;
23

    
24
import java.awt.geom.AffineTransform;
25
import java.awt.geom.NoninvertibleTransformException;
26
import java.awt.geom.Point2D;
27
import java.io.BufferedReader;
28
import java.io.File;
29
import java.io.FileReader;
30

    
31
import org.cresques.cts.ICoordTrans;
32
import org.gvsig.fmap.dal.DALFileLocator;
33
import org.gvsig.fmap.dal.DALLocator;
34
import org.gvsig.fmap.dal.DataStore;
35
import org.gvsig.fmap.dal.coverage.RasterLocator;
36
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
37
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
38
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
39
import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
40
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
41
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
42
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
43
import org.gvsig.fmap.dal.coverage.exception.ParsingException;
44
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
45
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
46
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
47
import org.gvsig.fmap.dal.coverage.store.parameter.RasterFileStoreParameters;
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.cache.tile.provider.TileServer;
53
import org.gvsig.raster.impl.buffer.SpiRasterQuery;
54
import org.gvsig.raster.impl.datastruct.ExtentImpl;
55
import org.gvsig.raster.impl.process.RasterTask;
56
import org.gvsig.raster.impl.process.RasterTaskQueue;
57
import org.gvsig.raster.impl.provider.AbstractRasterProvider;
58
import org.gvsig.raster.impl.provider.RasterProvider;
59
import org.gvsig.raster.impl.provider.tile.FileTileServer;
60
import org.gvsig.raster.impl.store.AbstractRasterDataParameters;
61
import org.gvsig.raster.impl.store.DefaultRasterStore;
62
import org.gvsig.raster.impl.store.DefaultStoreFactory;
63
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
64
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
65
import org.gvsig.tools.ToolsLocator;
66
import org.gvsig.tools.task.TaskStatus;
67

    
68
import com.ermapper.ecw.JNCSException;
69
import com.ermapper.ecw.JNCSFile;
70
import com.ermapper.ecw.JNCSFileNotOpenException;
71
import com.ermapper.ecw.JNCSInvalidSetViewException;
72
import com.ermapper.ecw.JNCSProgressiveUpdate;
73
/**
74
 * Driver de Ecw
75
 *
76
 * @author Nacho Brodin (nachobrodin@gmail.com)
77
 */
78
public class ErmapperProvider extends AbstractRasterProvider implements JNCSProgressiveUpdate {
79
        //private static final Logger           logger                   = LoggerFactory.getLogger(ErmapperProvider.class);
80
        public static String                  NAME                     = "Ermapper Store";
81
        public static String                  DESCRIPTION              = "Ermapper Raster file";
82
        public static final String            METADATA_DEFINITION_NAME = "ErmapperStore";
83
        private JNCSFile                                       file                     = null;
84
        protected Transparency                        fileTransparency         = null;
85
        private Extent                        viewRequest              = null;
86
        private DataStoreColorInterpretation  colorInterpr             = null;
87
        private boolean                       open                     = false;
88
        protected static String[]             formatList               = null;
89
        
90
        public static void register() {
91
                RasterLocator.getManager().getProviderServices().registerFileProvidersTiled(ErmapperProvider.class);
92
                registerFormats();
93
                
94
                DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
95
                if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
96
                        dataman.registerStoreProvider(NAME,
97
                                        ErmapperProvider.class, 
98
                                        ErmapperDataParameters.class);
99
                }
100
                
101
                if(DALFileLocator.getFilesystemServerExplorerManager() != null)
102
                        DALFileLocator.getFilesystemServerExplorerManager().registerProvider(
103
                                        NAME, 
104
                                        DESCRIPTION,
105
                                        ErmapperFilesystemServerExplorer.class);
106
                
107
            dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
108
        }
109
        
110
        private static void registerFormats() {
111
                formatList      = new String[] {
112
                                "ecw", 
113
                                "jp2"};
114
                for (int i = 0; i < formatList.length; i++) 
115
                        RasterLocator.getManager().getProviderServices().addFormat(formatList[i], ErmapperProvider.class);
116
        }
117
        
118
        public String[] getFormatList() {
119
                return formatList;
120
        }
121
        
122
        /**
123
         * Returns true if the extension is supported and false if doesn't
124
         * @param ext
125
         * @return
126
         */
127
        public boolean isExtensionSupported(String ext) {
128
                if(ext.indexOf(".") != -1)
129
                        ext = ext.substring(ext.lastIndexOf(".") + 1, ext.length());
130
                for (int i = 0; i < formatList.length; i++) {
131
                        if(formatList[i].compareTo(ext) == 0)
132
                                return true;
133
                }
134
                return false;
135
        }
136
        
137
        /**
138
         * Mandatory constructor to instantiate an empty provider
139
         */
140
        public ErmapperProvider() {
141
        }
142
        
143
        /**
144
         * Constructor. Abre el dataset.
145
         * @param proj Proyecci?n
146
         * @param fName Nombre del fichero ecw
147
         * @throws NotSupportedExtensionException
148
         */
149
        public ErmapperProvider(String params) throws NotSupportedExtensionException {
150
                super(params);
151
                if(params instanceof String) {
152
                        ErmapperDataParameters p = new ErmapperDataParameters();
153
                        p.setURI((String)params);
154
                        super.init(p, null, ToolsLocator.getDynObjectManager()
155
                                        .createDynObject(
156
                                                        MetadataLocator.getMetadataManager().getDefinition(
157
                                                                        DataStore.METADATA_DEFINITION_NAME)));
158
                        init(p, null);
159
                }
160
        }
161
        
162
        public ErmapperProvider(ErmapperDataParameters params,
163
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
164
                super(params, storeServices, ToolsLocator.getDynObjectManager()
165
                                .createDynObject(
166
                                                MetadataLocator.getMetadataManager().getDefinition(
167
                                                                DataStore.METADATA_DEFINITION_NAME)));
168
                init(params, storeServices);
169
        }
170

    
171
        /**
172
         * Abre el dataset.
173
         * @param proj Proyecci?n
174
         * @param fName Nombre del fichero ecw
175
         * @throws NotSupportedExtensionException
176
         */
177
        public void init (AbstractRasterDataParameters params,
178
                        DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
179
                setParam(storeServices, params);
180
                if (!((RasterFileStoreParameters)param).getFile().exists() && !((RasterDataParameters)param).getURI().startsWith("ecwp:"))
181
                        throw new NotSupportedExtensionException("Extension not supported");
182

    
183
                try {
184
                        file = new JNCSFile(((RasterDataParameters)param).getURI(), false);
185
                } catch (JNCSException e1) {
186
                        throw new NotSupportedExtensionException("Error loading the ecw file", e1);
187
                }
188
                
189
                /*
190
                 * TODO: Leer proyecciones ECW
191
                 * 
192
                 wktProjection = null;//getWKTFromEcw_csFile(file.projection);
193
                if(wktProjection != null && wktProjection != "") {
194
                        try {
195
                                proj = RasterLocator.getManager().getCRSUtils().convertWktToIProjection(wktProjection);
196
                        } catch (Exception e) {
197
                                logger.info("Error reading WKT from the raster provider", e);
198
                        }
199
                }*/
200
                
201
                load();
202
                bandCount = file.numBands;
203

    
204
                int[] dt = new int[bandCount];
205
                for (int i = 0; i < bandCount; i++)
206
                        dt[i] = Buffer.TYPE_BYTE;
207
                setDataType(dt);
208

    
209
                super.init();
210

    
211
                try {
212
                        loadFromRmf(getRmfBlocksManager());
213
                } catch (ParsingException e) {
214
                        //No lee desde rmf
215
                }
216
                open = true;
217
        }
218
        
219
        @SuppressWarnings("unused")
220
        private String getWKTFromEcw_csFile(String identifier) {
221
                File file = new File("./");
222
                file = new File(file.getAbsoluteFile() + File.separator + "data" + File.separator + "gdal" + File.separator + "ecw_cs.wkt");
223
                if(file.exists()) {
224
                        FileReader fr = null;
225
                        BufferedReader br = null;
226
                        try {
227
                                fr = new FileReader(file);
228
                                br = new BufferedReader(fr);
229

    
230
                                String line;
231
                                while((line = br.readLine()) != null) {
232
                                        if(line.startsWith(identifier + ",")) {
233
                                                int index = line.indexOf(",") + 1;
234
                                                return line.substring(index);
235
                                        }
236
                                }
237
                        } catch(Exception e){
238
                                return null;
239
                        } finally {
240
                                try {                   
241
                                        if(fr != null) 
242
                                                fr.close();                   
243
                                } catch (Exception e2){
244
                                        e2.printStackTrace();
245
                                }
246
                        }
247
                }
248
                return null;
249
        }
250

    
251
        public RasterProvider load() {
252
                ownTransformation = new AffineTransform(file.cellIncrementX, 0, 0, file.cellIncrementY, file.originX, file.originY);
253
                externalTransformation = (AffineTransform) ownTransformation.clone();
254
                return this;
255
        }
256
        
257
        public boolean isOpen() {
258
                return open;
259
        }
260

    
261
        public void close() {
262
                if(file != null) {
263
                        open = false;
264
                        //Cuando se abren varios datastores del mismo fichero y se cierra uno de ellos se cierra la aplicaci?n en el siguiente dibujado
265
                        //Se deber?a buscar una soluci?n ya que en los PrepareLayer se abre y cierra para hacer comprobaciones.
266
                        //file.close(false);
267
                        file = null;
268
                }
269
        }
270

    
271
        public Transparency getTransparency() {
272
                if(fileTransparency == null)
273
                        fileTransparency = new DataStoreTransparency(getColorInterpretation());
274
                return fileTransparency;
275
        }
276

    
277
        public double getWidth() {
278
                return file.width;
279
        }
280

    
281
        public double getHeight() {
282
                return file.height;
283
        }
284

    
285
        public Extent getView() {
286
                return viewRequest;
287
        }
288

    
289
        public void setView(Extent e) {
290
                viewRequest = new ExtentImpl(e);
291
        }
292
        
293
        @Override
294
        public void loadBuffer(SpiRasterQuery query)
295
                        throws ProcessInterruptedException, RasterDriverException {
296
                setView(transformExternalGeorefToOwnGeoref(query.getAdjustedRequestBoundingBox()));
297
                int bufWidth = query.getAdjustedBufWidth();
298
                int bufHeight = query.getAdjustedBufHeight();
299
                int[] stpBuffer = new int[]{0, 0 , bufWidth, bufHeight};
300
                loadBuffer(viewRequest, 
301
                                bufWidth, 
302
                                bufHeight, 
303
                                query.getBufferForProviders(), 
304
                                query.getBandList(), 
305
                                stpBuffer, 
306
                                query.getTaskStatus());
307
        }
308
        
309
        /**
310
         * Converts coordinates from the external transformation to the own transformation.
311
         * This is useful when the user assigns a transformation or the own raster has one
312
         * in the rmf file. Ecw need this function because the data window are requested to 
313
         * the library in world coordinates.
314
         * @param ext
315
         * @return
316
         */
317
        private Extent transformExternalGeorefToOwnGeoref(Extent ext) {
318
                if(externalTransformation.equals(ownTransformation))
319
                        return ext;
320
                
321
                Point2D ul = ext.getUL();
322
                Point2D lr = ext.getLR();
323
                
324
                Point2D p1 = new Point2D.Double();
325
                Point2D p2 = new Point2D.Double();
326
                
327
                try {
328
                        externalTransformation.inverseTransform(ul, p1);
329
                } catch (NoninvertibleTransformException e) {
330
                        e.printStackTrace();
331
                }
332
                ownTransformation.transform(p1, p1);
333
                
334
                try {
335
                        externalTransformation.inverseTransform(lr, p2);
336
                } catch (NoninvertibleTransformException e) {
337
                        e.printStackTrace();
338
                }
339
                ownTransformation.transform(p2, p2);
340
                
341
                return RasterLocator.getManager().getDataStructFactory().createExtent(p1, p2);
342
        }
343

    
344
        /**
345
         * Carga el buffer con las bandas RGB del raster con los par?metros especificados de extensi?n
346
         * y tama?o de buffer. El problema de ecw es que solo podemos leer 3 bandas de una vez ya que solo disponemos
347
         * de una llamada readLineRGBA. Para leer m?s bandas tendremos que hacer multiples llamadas a setView para leer
348
         * 3 cada vez.
349
         *
350
         * Si por ejemplo tenemos un ecw de 6 bandas [0, 1, 2, 3, 4, 5] y queremos cargar un buffer con el siguiente orden
351
         * [0, -, 2, -, 4, -] La variable readBandsFromECW har? la llamada a setView con los valores [0, 2, 4, 0, 0, 0]. La
352
         * funci?n drawRGB ser? la encargada de hacer el switch para obtener [0, -, 2, -, 4, -].
353
         *
354
         * Bug#1: Si se dispone de un ecw de m?s de tres bandas podemos llamar a setView con readBandsFromECW con el orden
355
         * que queramos, por ejemplo [3, 2, 5, 1, 0] pero para ecw de 3 bandas la llamada con las bandas cambiadas no
356
         * hace caso. El caso de readBandsFromECW = [2, 0, 1] ser? tomado siempre como [0, 1, 2].
357
         *
358
         * @param selectedExtent Extensi?n seleccionada
359
         * @param bufWidth Ancho de buffer
360
         * @param bufHeight Alto de buffer
361
         * @param rasterBuf Buffer de datos
362
         */
363
        private void loadBuffer(Extent selectedExtent, 
364
                        int bufWidth, 
365
                        int bufHeight, 
366
                        Buffer rasterBuf, 
367
                        BandList bandList, 
368
                        int[] stpBuffer,
369
                        TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
370
                try {
371
                        RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
372
                        
373
                        int[] readBandsFromECW = new int[Math.max(file.numBands, 3)];
374
                        
375
                        for(int i = 0; i < readBandsFromECW.length; i ++) {
376
                                readBandsFromECW[i] = i;
377
                        }
378

    
379
                        if(task.getEvent() != null)
380
                                task.manageEvent(task.getEvent());
381
                        if(status != null && status.isCancelled())
382
                                return;
383

    
384
                        if(bufWidth > Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX)))
385
                                bufWidth = (int)Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX));
386
                        if(bufHeight > Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY)))
387
                                bufHeight = (int)Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY));
388
                        file.setView(file.numBands, readBandsFromECW, selectedExtent.minX(), selectedExtent.maxY(), selectedExtent.maxX(), selectedExtent.minY(), bufWidth, bufHeight);
389
                        
390
                        //Escribimos el raster sobre un Buffer
391
                        int[] pRGBArray = new int[bufWidth];
392
                        drawRGB2(rasterBuf, pRGBArray, bandList, status);
393

    
394
                }catch(JNCSInvalidSetViewException exc){
395
                        throw new RasterDriverException("Error setting coords");
396
                }catch (JNCSFileNotOpenException e) {
397
                        throw new RasterDriverException("Error opening file");
398
                }catch (JNCSException ex) {
399
                        throw new RasterDriverException("Error reading data");
400
                }
401

    
402
        }
403
        
404
        private void drawRGB2(
405
                        Buffer rasterBuf, 
406
                        int[] pRGBArray, 
407
                        BandList bandList, 
408
                        TaskStatus status) throws JNCSException, ProcessInterruptedException {
409
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
410
                int[] drawableBands = null;
411
                
412
                for (int line = 0; line < rasterBuf.getHeight(); line++) {
413
                        try {
414
                                file.readLineRGBA(pRGBArray);
415
                                for(int col = 0; col < pRGBArray.length; col ++) {
416
                                        drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 0);
417
                                        if(drawableBands != null) {
418
                                                for (int i = 0; i < drawableBands.length; i++) {
419
                                                        if(drawableBands[i] != -1)
420
                                                                rasterBuf.setElem(line, col, drawableBands[i], (byte)((pRGBArray[col] & 0x00ff0000) >> 16));                                                        
421
                                                }
422
                                        }
423
                                        drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 1);
424
                                        if(drawableBands != null) {
425
                                                for (int i = 0; i < drawableBands.length; i++) {
426
                                                        if(drawableBands[i] != -1)
427
                                                                rasterBuf.setElem(line, col, drawableBands[i], (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
428
                                                }
429
                                        }
430
                                        drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 2);
431
                                        if(drawableBands != null) {
432
                                                for (int i = 0; i < drawableBands.length; i++) {
433
                                                        if(drawableBands[i] != -1)
434
                                                                rasterBuf.setElem(line, col, drawableBands[i], (byte)(pRGBArray[col] & 0x000000ff));
435
                                                }
436
                                        }
437
                                }
438
                        } catch (JNCSException exc) {
439
                        }
440
                        if(task.getEvent() != null)
441
                                task.manageEvent(task.getEvent());
442
                        if(status != null && status.isCancelled())
443
                                return;
444
                }
445
                return;
446
        }
447

    
448
        @SuppressWarnings("unused")
449
        private void drawRGB(Buffer rasterBuf, int[] pRGBArray, int[] readBands, BandList bandList, RasterTask task) throws JNCSException, ProcessInterruptedException {
450
                int bandR = readBands[0];
451
                int bandG = (readBands.length > 1) ? readBands[1] : -1;
452
                int bandB = (readBands.length > 2) ? readBands[2] : -1;
453

    
454
                //********* caso especial que resuelve Bug#1 **********************
455
                if(file.numBands == 3 && bandList.getDrawableBandsCount() < 3) {
456
                        for(int i = 0; i < 3; i ++) {
457
                                int[] b = bandList.getBand(i).getBufferBandListToDraw();
458
                                if(b != null){
459
                                        bandG = 1; bandR = 0; bandB = 2;
460
                                }
461
                        }
462
                }
463
                if(file.numBands == 3 && bandR == bandG && bandG == bandB) { //caso especial que resuelve Bug#1
464
                        for(int i = 0; i < 3; i ++) {
465
                                int[] b = bandList.getBand(i).getBufferBandListToDraw();
466
                                if(b != null) {
467
                                        if(i == 0) {
468
                                                for (int line = 0; line < rasterBuf.getHeight(); line++) {
469
                                                        try {
470
                                                                file.readLineRGBA(pRGBArray);
471
                                                                for(int col = 0; col < pRGBArray.length; col ++) {
472
                                                                        rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
473
                                                                        rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
474
                                                                        rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
475
                                                                }
476
                                                        } catch (JNCSException exc) {
477
                                                        }
478
                                                }
479
                                                return;
480
                                        }
481
                                        if(i == 1) {
482
                                                for (int line = 0; line < rasterBuf.getHeight(); line++) {
483
                                                        try {
484
                                                                file.readLineRGBA(pRGBArray);
485
                                                                for(int col = 0; col < pRGBArray.length; col ++) {
486
                                                                        rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
487
                                                                        rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
488
                                                                        rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
489
                                                                }
490
                                                        } catch (JNCSException exc) {
491
                                                        }
492
                                                }
493
                                                return;
494
                                        }
495
                                        if(i == 2) {
496
                                                for (int line = 0; line < rasterBuf.getHeight(); line++) {
497
                                                        try {
498
                                                                file.readLineRGBA(pRGBArray);
499
                                                                for(int col = 0; col < pRGBArray.length; col ++) {
500
                                                                        rasterBuf.setElem(line, col, bandR, (byte)(pRGBArray[col] & 0x000000ff));
501
                                                                        rasterBuf.setElem(line, col, bandG, (byte)(pRGBArray[col] & 0x000000ff));
502
                                                                        rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
503
                                                                }
504
                                                        } catch (JNCSException exc) {
505
                                                        }
506
                                                }
507
                                                return;
508
                                        }
509
                                }
510
                                if(task.getEvent() != null)
511
                                        task.manageEvent(task.getEvent());
512
                        }
513

    
514
                }
515
                //********* END caso especial que resuelve Bug#1 **********************
516

    
517
                if(bandR >= 0 && bandG >= 0 && bandB >= 0) {
518
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
519
                                try {
520
                                        file.readLineRGBA(pRGBArray);
521
                                        for(int col = 0; col < pRGBArray.length; col ++) {
522
                                                rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
523
                                                rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
524
                                                rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
525
                                        }
526
                                } catch (JNCSException exc) {
527
                                }
528
                        }
529
                        return;
530
                }
531

    
532
                if(task.getEvent() != null)
533
                        task.manageEvent(task.getEvent());
534

    
535
                if(bandR >= 0 && bandG >= 0) {
536
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
537
                                try {
538
                                        file.readLineRGBA(pRGBArray);
539
                                        for(int col = 0; col < pRGBArray.length; col ++) {
540
                                                rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
541
                                                rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
542
                                        }
543
                                } catch (JNCSException exc) {
544
                                }
545
                        }
546
                        return;
547
                }
548

    
549
                if(task.getEvent() != null)
550
                        task.manageEvent(task.getEvent());
551

    
552
                if(bandR >= 0){
553
                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
554
                                try {
555
                                        file.readLineRGBA(pRGBArray);
556
                                        for(int col = 0; col < pRGBArray.length; col ++)
557
                                                rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
558
                                } catch (JNCSException exc) {
559
                                }
560
                        }
561
                        return;
562
                }
563

    
564
                if(task.getEvent() != null)
565
                        task.manageEvent(task.getEvent());
566

    
567
        }
568

    
569
        public void reProject(ICoordTrans rp) {
570
        }
571

    
572
        public int getBlockSize() {
573
                return 0;
574
        }
575

    
576
        public Object readCompleteLine(int line, int band) throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
577
                if(line < 0 || line >= file.height || band < 0 || band >= getBandCount())
578
                        throw new InvalidSetViewException("Request out of grid");
579

    
580
                Point2D begin = rasterToWorld(new Point2D.Double(0, line));
581
                Point2D end = rasterToWorld(new Point2D.Double(file.width, line + 1));
582
                int[] readBandsFromECW = new int[file.numBands];
583
                if(file.numBands <= 3) {
584
                        for(int i = 0; i < file.numBands; i++)
585
                                readBandsFromECW[i] = i;
586
                } else {
587
                        readBandsFromECW[0] = band;
588
                }
589

    
590
                Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
591

    
592
                try {
593
                        int[] value = new int[file.width];
594
                        file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, 1);
595
                        file.readLineRGBA(value);
596

    
597
                        if(file.numBands <= 3) {
598
                                switch(getDataType()[0]) {
599
                                case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
600
                                                                                switch(band) {
601
                                                                                case 0: for(int i = 0; i < file.width; i ++)
602
                                                                                                        b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
603
                                                                                                break;
604
                                                                                case 1: for(int i = 0; i < file.width; i ++)
605
                                                                                                        b[i] = (byte)(((value[i] & 0x0000ff00) >> 8) & 0xff);
606
                                                                                                break;
607
                                                                                case 2: for(int i = 0; i < file.width; i ++)
608
                                                                                                        b[i] = (byte)((value[i] & 0x000000ff) & 0xff);
609
                                                                                                break;
610
                                                                                }
611
                                                                                return b;
612
                                }
613
                        }else {
614
                                switch(getDataType()[0]) {
615
                                case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
616
                                                                                for(int i = 0; i < file.width; i ++)
617
                                                                                        b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
618
                                                                                break;
619
                                }
620
                        }
621
                        //TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
622
                } catch (JNCSFileNotOpenException e1) {
623
                        throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
624
                } catch (JNCSInvalidSetViewException e1) {
625
                        throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
626
                } catch (JNCSException e1) {
627
                        throw new RasterDriverException("Error la lectura de datos ecw");
628
                }
629

    
630
                return null;
631
        }
632

    
633
        public Object readBlock(int pos, int blockHeight, double scale) throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
634
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
635
                if(pos < 0)
636
                        throw new InvalidSetViewException("Request out of grid");
637

    
638
                if((pos + blockHeight) > file.height)
639
                        blockHeight = Math.abs(file.height - pos);
640

    
641
                Point2D begin = rasterToWorld(new Point2D.Double(0, pos));
642
                Point2D end = rasterToWorld(new Point2D.Double(file.width, pos + blockHeight));
643
                int[] readBandsFromECW = new int[file.numBands];
644

    
645
                for(int i = 0; i < file.numBands; i++)
646
                        readBandsFromECW[i] = i;
647

    
648
                byte[][][] buf = new byte[file.numBands][blockHeight][file.width];
649
                Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
650
                e = rasterUtil.calculateAdjustedView(getExtent(), e);
651

    
652
                try {
653
                        int[] value = new int[file.width];
654
                        file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, blockHeight);
655

    
656
                        if(file.numBands <= 3) {
657
                                for (int row = 0; row < blockHeight; row++) {
658
                                        file.readLineRGBA(value);
659
                                        switch(getDataType()[0]) {
660
                                        case Buffer.TYPE_BYTE:
661
                                                if(buf.length >= 3) {
662
                                                        for(int col = 0; col < file.width; col ++) {
663
                                                                buf[0][row][col] = (byte)(((value[col] & 0x00ff0000) >> 16) & 0xff);
664
                                                                buf[1][row][col] = (byte)(((value[col] & 0x0000ff00) >> 8) & 0xff);
665
                                                                buf[2][row][col] = (byte)((value[col] & 0x000000ff) & 0xff);
666
                                                        }
667
                                                } else { //Si es monobanda solo se usa cualquiera uno de los tres valores
668
                                                        for(int col = 0; col < file.width; col ++) {
669
                                                                buf[0][row][col] = (byte)(((value[col] & 0x00ff0000) >> 16) & 0xff);
670
                                                        }
671
                                                }
672
                                                break;
673
                                        }
674
                                }
675

    
676
                                if(task.getEvent() != null)
677
                                        task.manageEvent(task.getEvent());
678

    
679
                        } else {
680
                                //TODO: FUNCIONALIDAD: file.numBands > 3
681
                        }
682

    
683
                        //TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
684
                } catch (JNCSFileNotOpenException e1) {
685
                        throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
686
                } catch (JNCSInvalidSetViewException e1) {
687
                        throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
688
                } catch (JNCSException e1) {
689
                        throw new RasterDriverException("Error la lectura de datos ecw");
690
                }
691

    
692
                return buf;
693
        }
694

    
695
        public Object getData(int x, int y, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
696
                if(x < 0 || y < 0 || x >= file.width || y >= file.height)
697
                        throw new InvalidSetViewException("Request out of grid");
698

    
699
                Point2D begin = new Point2D.Double(x, y);
700
                Point2D end = new Point2D.Double(x + 1, y + 1);
701

    
702
                ownTransformation.transform(begin, begin);
703
                ownTransformation.transform(end, end);
704

    
705
                int[] readBandsFromECW = new int[file.numBands];
706
                if(file.numBands <= 3){
707
                        for(int i = 0; i < file.numBands; i++)
708
                                readBandsFromECW[i] = i;
709
                }else{
710
                        readBandsFromECW[0] = band;
711
                }
712

    
713
                Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
714
                try {
715
                        int[] value = new int[1];
716
                        file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), 1, 1);
717
                        file.readLineRGBA(value);
718
                        if(file.numBands <= 3){
719
                                switch(band){
720
                                case 0: return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
721
                                case 1: return new Integer((((value[0] & 0x0000ff00) >> 8) & 0xffffffff));
722
                                case 2: return new Integer((((value[0] & 0x000000ff)) & 0xffffffff));
723
                                }
724
                        }
725
                        return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
726
                } catch (JNCSFileNotOpenException e1) {
727
                        throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
728
                } catch (JNCSInvalidSetViewException e1) {
729
                        throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
730
                } catch (JNCSException e1) {
731
                        throw new RasterDriverException("Error reading ecw data");
732
                }
733
        }
734

    
735
        public void refreshUpdate(int arg0, int arg1, double arg2, double arg3, double arg4, double arg5) {
736
        }
737

    
738
        public void refreshUpdate(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
739
        }
740

    
741
        public DataStoreColorInterpretation getColorInterpretation() {
742
                if(colorInterpr == null) {
743
                        colorInterpr = new DataStoreColorInterpretation();
744
                        colorInterpr.initColorInterpretation(getBandCount());
745
                        if(getBandCount() == 1)
746
                                colorInterpr = DataStoreColorInterpretation.createGrayInterpretation();
747
                        if(getBandCount() == 3) {
748
                                colorInterpr =  DataStoreColorInterpretation.createRGBInterpretation();
749
                        }
750
                        if(getBandCount() >= 4) {
751
                                colorInterpr = DataStoreColorInterpretation.createRGBAInterpretation();
752
                        }
753
                }
754
                return colorInterpr;
755
        }
756

    
757
        public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
758
                if(band >= getBandCount())
759
                        throw new BandAccessException("Wrong band");
760
                return 0;
761
        }
762

    
763
        public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
764
                if (band >= getBandCount())
765
                        throw new BandAccessException("Wrong band");
766
                return 0;
767
        }
768

    
769
        public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
770
                if (band >= getBandCount())
771
                        throw new BandAccessException("Wrong band");
772
                return 0;
773
        }
774

    
775
        public boolean isOverviewsSupported() {
776
                return false;
777
        }
778

    
779
        
780
        public String getStringProjection() throws RasterDriverException{
781
                return file.projection;
782
        }
783

    
784
        public String getWktProjection() {
785
                return null;
786
        }
787
        
788
        public String getName() {
789
                return NAME;
790
        }
791
        
792
        public void setStatus(RasterProvider provider) {
793
                if(provider instanceof ErmapperProvider) {
794
                        //Not implemented yet
795
                }
796
        }
797
        
798
        public boolean isSupersamplingSupported() {
799
                return false;
800
        }
801
        
802
        public TileServer getTileServer() {
803
                if(tileServer == null) {
804
                        DefaultRasterStore store = new DefaultRasterStore();
805
                        store.setProvider(this);
806
                        tileServer = new FileTileServer(store);
807
                }
808
                return tileServer;
809
        }
810
}