Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1010 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / operations / strategies / ShpStrategy.java @ 12804

History | View | Annotate | Download (23.2 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.fmap.operations.strategies;
42

    
43
import java.awt.Graphics2D;
44
import java.awt.geom.Point2D;
45
import java.awt.geom.Rectangle2D;
46
import java.awt.image.BufferedImage;
47
import java.io.IOException;
48
import java.util.BitSet;
49
import java.util.List;
50

    
51
import javax.print.attribute.PrintRequestAttributeSet;
52

    
53
import org.apache.log4j.Logger;
54
import org.cresques.cts.ICoordTrans;
55
import org.geotools.resources.geometry.XRectangle2D;
56

    
57
import com.hardcode.driverManager.DriverLoadException;
58
import com.iver.cit.gvsig.fmap.DriverException;
59
import com.iver.cit.gvsig.fmap.ViewPort;
60
import com.iver.cit.gvsig.fmap.core.FShape;
61
import com.iver.cit.gvsig.fmap.core.IGeometry;
62
import com.iver.cit.gvsig.fmap.core.ISymbol;
63
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
64
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
65
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
66
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
67
import com.iver.cit.gvsig.fmap.layers.FBitSet;
68
import com.iver.cit.gvsig.fmap.layers.FLayer;
69
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
70
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
71
import com.iver.cit.gvsig.fmap.layers.SpatialCache;
72
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
73
import com.iver.cit.gvsig.fmap.layers.layerOperations.Selectable;
74
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
75
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
76
import com.iver.utiles.swing.threads.Cancellable;
77
import com.iver.utiles.swing.threads.CancellableMonitorable;
78
import com.vividsolutions.jts.geom.Geometry;
79
import com.vividsolutions.jts.geom.IntersectionMatrix;
80

    
81
/**
82
 * Esta clase definir? las operaciones de la interfaz FLyrVect de la manera m?s
83
 * ?ptima para los ficheros shp.
84
 */
85
public class ShpStrategy extends DefaultStrategy {
86
        private static Logger logger = Logger
87
                        .getLogger(ShpStrategy.class.getName());
88

    
89
        /**
90
         * Crea una ShpStrategy.
91
         *
92
         * @param capa
93
         */
94
        public ShpStrategy(FLayer capa) {
95
                super(capa);
96
        }
97

    
98
        /**
99
         * @see com.iver.cit.gvsig.fmap.operations.LayerOperations#draw(java.awt.image.BufferedImage,
100
         *      java.awt.Graphics2D, ISymbol)
101
         */
102
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
103
                        Cancellable cancel) throws DriverException {
104
                try {
105
                        ReadableVectorial adapter = ((SingleLayer) getCapa()).getSource();
106
                        if (adapter.getShapeCount() <= 0) {
107
                                // logger.info("Layer:" + getCapa().getName() + " sin
108
                                // registros");
109
                                return;
110
                        }
111

    
112
                        // Selectable selection = (Selectable) getCapa();
113
                        FLyrVect lyr = (FLyrVect) getCapa();
114
                        Selectable selectable = lyr.getRecordset();
115
                        ICoordTrans ct = getCapa().getCoordTrans();
116
                        FBitSet bitSet = selectable.getSelection();
117
                        BoundedShapes shapeBounds;
118
                        if (adapter instanceof BoundedShapes)
119
                                shapeBounds = (BoundedShapes) adapter;
120
                        else
121
                                shapeBounds = (BoundedShapes) adapter.getDriver();
122
                        // VectorialFileDriver driver = (VectorialFileDriver)
123
                        // adapter.getDriver();
124
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
125
                        adapter.start();
126
                        IGeometry geom;
127
                        // if (adapter.getShapeCount() > 0) {
128
                        // geom = adapter.getShape(0);
129
                        // }
130
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa())
131
                                        .getLegend();
132

    
133
//                        if (l instanceof ClassifiedLegendInfo) {
134
//                                ClassifiedLegendInfo clsfLegend = (ClassifiedLegendInfo) l;
135
//                                ISymbol[] symbs = clsfLegend.getSymbols();
136
//                                // double rSym = 0;
137
//                                // double maxRSym = -1;
138
//
139
//                                for (int i = 0; i < symbs.length; i++) {
140
//                                        // TODO: REVISAR LOS SIMBOLOS Y SUS TAMA?OS
141
//
142
//                                        /*
143
//                                         * Style2D pointSymbol = symbs[i].getPointStyle2D(); if
144
//                                         * (pointSymbol instanceof MarkStyle2D) { MarkStyle2D mrk2D =
145
//                                         * (MarkStyle2D) pointSymbol; rSym =
146
//                                         * viewPort.toMapDistance(mrk2D.getSize()); if (maxRSym <
147
//                                         * rSym) maxRSym = rSym; }
148
//                                         */
149
//                                }
150
//                        }
151

    
152
                        Rectangle2D extent = viewPort.getAdjustedExtent();
153
                        // AffineTransform at = viewPort.getAffineTransform();
154

    
155
                        int sc;
156

    
157
                        Rectangle2D bounds;
158

    
159
                        long t1 = System.currentTimeMillis();
160
                        // logger.debug("getCapa().getRecordset().start()");
161

    
162
                        //CHEMA
163
                        // En teorioa el al hacer el adapter.start()
164
                        // deja abierta las fuentes de datos
165
                        // geometrica y alfanumerica (cuando no son la misma
166
                        // excepto cuando se ha hecho una operacion de 'join' de la tabla
167
                        // (join de las tablas de gvsig(gdbms) no join de sql), entoces
168
                        // el origen alfanumerico no es el mismo en el source
169
                        // que en la capa.
170
                        //
171
                        //((FLyrVect) getCapa()).getRecordset().start();
172
                        if (lyr.isJoined()){
173
                                lyr.getRecordset().start();
174
                        }
175
                        //CHEMA
176

    
177
                        // TODO: A revisar si es o no conveniente este sistema
178
                        // de comunicaci?n con los drivers.
179
                        DriverAttributes attr = adapter.getDriverAttributes();
180
                        boolean bMustClone = false;
181
                        if (attr != null) {
182
                                if (attr.isLoadedInMemory()) {
183
                                        bMustClone = attr.isLoadedInMemory();
184
                                }
185
                        }
186

    
187
                        List lstIndexes = null;
188

    
189
                        // If area of needed extent is less than fullExtent / 4,
190
                        // it will be worthy to use SpatialIndex.
191
                        // Otherwhise, we will not use it.
192
                        boolean bUseSpatialIndex = false;
193
                        sc = adapter.getShapeCount();
194
                        // if (lyr.getSpatialIndex() != null) AZABALA
195
                        // long t11 = System.currentTimeMillis();
196
                        if (lyr.getISpatialIndex() != null) {
197
                                if (isSpatialIndexNecessary(extent)) {
198
                                        lstIndexes = lyr.getISpatialIndex().query(extent);
199
                                        // If the layer is reprojected, spatial index was created
200
                                        // in its own projection, so we must to apply an inverse
201
                                        // transform
202
                                        if (ct != null) {
203
                                                Rectangle2D newExtent = ct.getInverted()
204
                                                                .convert(extent);
205
                                                // Rectangle2D newExtent = ct.convert(extent);
206
                                                // lstIndexes = lyr.getISpatialIndex().query(extent);
207
                                                lstIndexes = lyr.getISpatialIndex().query(newExtent);
208
                                        } else {
209
                                                lstIndexes = lyr.getISpatialIndex().query(extent);
210
                                        }
211
                                        sc = lstIndexes.size();
212
                                        bUseSpatialIndex = true;
213
                                }// if
214
                        }// if
215
                        /*
216
                         * long t12 = System.currentTimeMillis(); System.out.println("Tiempo
217
                         * en mirar el ?ndice espacial y recuperar los ?ndices:" +
218
                         * (t12-t11)); System.out.println("Numero de ?ndices:" + sc);
219
                         */
220

    
221
                        // SpatialCache cache = lyr.createSpatialCache();
222
                        lyr.getSpatialCache().clearAll();
223
                        SpatialCache cache = lyr.getSpatialCache();
224
                        int i;
225

    
226
                        // En OS X con renderer Quartz (JRE<6), mezclar setRGB con dibujado
227
                        // geometrico en mismo BufferedImage
228
                        // provoca ralentizaci?n brutal. Lo evitamos separando los setRGB en
229
                        // otro BufferedImage y juntandolos luego.
230
                        boolean MAC_OS_X = System.getProperty("os.name").toLowerCase()
231
                                        .startsWith("mac os x");
232
                        BufferedImage auxBI = null;
233
                        if (MAC_OS_X) {
234
                                auxBI = new BufferedImage(image.getWidth(), image.getHeight(),
235
                                                image.getType());
236
                        }
237
                        for (int aux = 0; aux < sc; aux++) {
238
                                // Salimos si alguien cancela
239

    
240
                                if (cancel != null) {
241
                                        // azabala (por si acaso, al arreglar bug de process)
242
                                        if (cancel.isCanceled()) {
243
                                                return;
244
                                        }
245
                                }
246
                                if (bUseSpatialIndex) {
247
                                        Integer idRec = (Integer) lstIndexes.get(aux);
248
                                        i = idRec.intValue();
249
                                } else {
250
                                        i = aux;
251
                                }
252
                                if (getCapa().isEditing())
253
                                        bounds=adapter.getShape(i).getBounds2D();
254
                                else
255
                                        bounds = shapeBounds.getShapeBounds(i);
256
                                if (bounds==null)
257
                                        continue;
258
                                if (ct != null) {
259
                                        bounds = ct.convert(bounds);
260
                                }
261
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
262
                                        ISymbol symbol = l.getSymbol(i);
263
                                        if (symbol == null)
264
                                                continue;
265

    
266
                                        if (bitSet.get(i)) {
267
                                                symbol = symbol.getSymbolForSelection();
268
                                        }
269

    
270

    
271

    
272
                                        boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
273

    
274
                                        if (bPoint
275
                                                        || ((bounds.getHeight() > viewPort.getDist1pixel()) || (bounds
276
                                                                        .getWidth() > viewPort.getDist1pixel()))) {
277
                                                geom = adapter.getShape(i);
278

    
279
                                                // PRUEBA DE VELOCIDAD
280
                                                // geom = ShapeFactory.createPolygon2D(new
281
                                                // GeneralPathX(bounds));
282

    
283

    
284
                                                //JMVIVO: OJO, No colnamos siempre porque
285
                                                // el FGeometry.drawInt (a diferencia del
286
                                                // FGeometry.draw) clona siempre la geometria
287
                                                // antes de pintarla (para transforma a enteros)
288
                                                if (ct != null) {
289
                                                        if (bMustClone)
290
                                                                geom = geom.cloneGeometry();
291
                                                        geom.reProject(ct);
292
                                                }
293
                                                if (lyr.isSpatialCacheEnabled()) {
294
                                                        if (cache.getMaxFeatures() >= cache.size()) {
295
                                                                // Ya reproyectado todo
296
                                                                cache.insert(bounds, geom);
297
                                                        }
298
                                                }
299

    
300
                                                // FJP: CAMBIO: Sabemos que vamos a dibujar sobre una
301
                                                // imagen, con coordenadas enteras, as?
302
                                                // que lo tenemos en cuenta.
303
                                                // ANTES: geom.draw(g, viewPort, symbol);
304
                                                // AHORA:
305
                                                geom.drawInts(g, viewPort, symbol);
306
                                                // geom.draw(g, viewPort, symbol);
307
                                                /*
308
                                                 * if (lyr.isEditing()) { if (bitSet.get(i)) { Handler[]
309
                                                 * handlers = geom.getHandlers(IGeometry.SELECTHANDLER);
310
                                                 * FGraphicUtilities.DrawHandlers(g,
311
                                                 * viewPort.getAffineTransform(), handlers); } }
312
                                                 */
313

    
314
                                        } else {
315
                                                Point2D.Double pOrig = new Point2D.Double(bounds
316
                                                                .getMinX(), bounds.getMinY());
317
                                                Point2D pDest, pDest2;
318

    
319
                                                pDest = viewPort.getAffineTransform().transform(pOrig,
320
                                                                null);
321
                                                pDest2 = g.getTransform().transform(pDest, null);
322

    
323
                                                int pixX = (int) pDest2.getX();
324
                                                int pixY = (int) pDest2.getY();
325
                                                if (symbol == null)
326
                                                        continue;
327
                                                if ((pixX > 0) && (pixX < image.getWidth())) {
328
                                                        if ((pixY > 0) && (pixY < image.getHeight())) {
329
                                                                if (MAC_OS_X) {
330
                                                                        auxBI.setRGB(pixX, pixY, symbol
331
                                                                                        .getOnePointRgb());
332
                                                                } else {
333
                                                                        image.setRGB(pixX, pixY, symbol
334
                                                                                        .getOnePointRgb());
335
                                                                }
336
                                                        }
337
                                                }
338
                                        }
339
                                }
340
                        }
341

    
342
                        if (MAC_OS_X) {
343
                                g.drawImage(auxBI, 0, 0, null);
344
                        }
345

    
346
                        // logger.debug("getCapa().getRecordset().stop()");
347
                        //CHEMA
348
                        // Cerramos la fuente alfanumerica cuando se ha hecho
349
                        // una operacion de 'join'
350
                        //((FLyrVect) getCapa()).getSource().getRecordset().stop();
351
                        if (lyr.isJoined()){
352
                                lyr.getRecordset().stop();
353
                        }
354
                        //CHEMA
355

    
356
                        long t2 = System.currentTimeMillis();
357
                        // logger.debug("adapter.stop()");
358
                        adapter.stop();
359

    
360
                        // System.out.println(t2 - t1);
361
                } catch (DriverIOException e) {
362
                        throw new DriverException(e);
363
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
364
                        throw new DriverException(e);
365
                } catch (DriverException e) {
366
                        throw new DriverException(e);
367
                } catch (IOException e) {
368
                        throw new DriverException(e);
369
                } catch (DriverLoadException e) {
370
                        // TODO Auto-generated catch block
371
                        e.printStackTrace();
372
                }
373
        }
374

    
375
        /**
376
         * M?todo utilizado para dibujar sobre el graphics que se pasa como
377
         * par?metro, pensado para utilizarse para imprimir.
378
         *
379
         * @param g
380
         *            Graphics2D
381
         * @param viewPort
382
         *            ViewPort.
383
         * @param cancel
384
         *
385
         * @throws DriverException
386
         */
387
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
388
                        PrintRequestAttributeSet printProperties) throws DriverException {
389
                // super.draw(null, g, viewPort, cancel); // Quiero ejecutar el draw del
390
                // padre, que es el que va sin acelaraci?n!!
391
                try {
392
                        ReadableVectorial adapter = ((SingleLayer) getCapa()).getSource();
393
                        if (adapter.getShapeCount() <= 0) {
394
                                // logger.info("Layer:" + getCapa().getName() + " sin
395
                                // registros");
396
                                return;
397
                        }
398
                        FLyrVect lyr = (FLyrVect) getCapa();
399
                        lyr.beforePrinting(printProperties);
400

    
401
                        Selectable selectable = lyr.getRecordset();
402
                        ICoordTrans ct = getCapa().getCoordTrans();
403
                        BitSet bitSet = selectable.getSelection();
404
                        BoundedShapes shapeBounds = (BoundedShapes) adapter.getDriver();
405
                        VectorialDriver driver = (VectorialDriver) adapter
406
                                        .getDriver();
407
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
408
                        adapter.start();
409
                        IGeometry geom;
410
                        if (adapter.getShapeCount() > 0) {
411
                                geom = adapter.getShape(0);
412
                        }
413
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa())
414
                                        .getLegend();
415

    
416
                        Rectangle2D extent = viewPort.getAdjustedExtent();
417
                        // AffineTransform at = viewPort.getAffineTransform();
418

    
419
                        int sc;
420

    
421
                        Rectangle2D bounds;
422

    
423
                        sc = adapter.getShapeCount();
424

    
425
                        long t1 = System.currentTimeMillis();
426
                        // logger.debug("getCapa().getRecordset().start()");
427

    
428
                        //CHEMA
429
                        // En teorioa el al hacer el adapter.start()
430
                        // deja abierta las fuentes de datos
431
                        // geometrica y alfanumerica (cuando no son la misma
432
                        // excepto cuando se ha hecho una operacion de 'join' de la tabla
433
                        // (join de las tablas de gvsig(gdbms) no join de sql), entoces
434
                        // el origen alfanumerico no es el mismo en el source
435
                        // que en la capa.
436
                        //
437
                        //((FLyrVect) getCapa()).getRecordset().start();
438
                        if (lyr.isJoined()){
439
                                lyr.getRecordset().start();
440
                        }
441
                        //CHEMA
442

    
443

    
444
                        // TODO: A revisar si es o no conveniente este sistema
445
                        // de comunicaci?n con los drivers.
446
                        DriverAttributes attr = adapter.getDriverAttributes();
447
                        boolean bMustClone = false;
448
                        if (attr != null) {
449
                                if (attr.isLoadedInMemory()) {
450
                                        bMustClone = attr.isLoadedInMemory();
451
                                }
452
                        }
453

    
454
                        List lstIndexes = null;
455

    
456
                        boolean bUseSpatialIndex = false;
457
                        if (lyr.getISpatialIndex() != null) {
458
                                if (isSpatialIndexNecessary(extent)) {
459
                                        lstIndexes = lyr.getISpatialIndex().query(extent);
460
                                        if (ct != null) {
461
                                                Rectangle2D newExtent = ct.getInverted()
462
                                                                .convert(extent);
463
                                                lstIndexes = lyr.getISpatialIndex().query(newExtent);
464
                                        } else {
465
                                                lstIndexes = lyr.getISpatialIndex().query(extent);
466
                                        }
467
                                        sc = lstIndexes.size();
468
                                        bUseSpatialIndex = true;
469
                                }// if
470
                        }// if
471

    
472
                        int i;
473
                        for (int aux = 0; aux < sc; aux++) {
474
                                if (bUseSpatialIndex) {
475
                                        Integer idRec = (Integer) lstIndexes.get(aux);
476
                                        i = idRec.intValue();
477
                                } else {
478
                                        i = aux;
479
                                }
480

    
481
                                bounds = shapeBounds.getShapeBounds(i);
482

    
483
                                if (ct != null) {
484
                                        bounds = ct.convert(bounds);
485
                                }
486

    
487
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
488
                                        ISymbol symbol = l.getSymbol(i);
489
                                        if (symbol == null)
490
                                                continue;
491
                                        if (bitSet.get(i)) {
492
                                                symbol = symbol.getSymbolForSelection();
493
                                        }
494

    
495
                                        //boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
496

    
497
                                        geom = driver.getShape(i);
498

    
499
                                        // PRUEBA DE VELOCIDAD
500
                                        // geom = ShapeFactory.createPolygon2D(new
501
                                        // GeneralPathX(bounds));
502

    
503
                                        // JMVIVO: Clonamos siempre que sea necesario y no
504
                                        // solo si hay que reproyectar. Porque el FGeometry.draw
505
                                        // va a aplicar la transformacion sobre la geometria original
506
                                        if (bMustClone)
507
                                                geom = geom.cloneGeometry();
508

    
509
                                        if (ct != null) {
510
                                                geom.reProject(ct);
511
                                        }
512

    
513
                                        geom.draw(g, viewPort, symbol);
514

    
515
                                }
516
                        }
517

    
518
                        // logger.debug("getCapa().getRecordset().stop()");
519
                        //CHEMA
520
                        // Cerramos la fuente alfanumerica cuando se ha hecho
521
                        // una operacion de 'join'
522
                        //((FLyrVect) getCapa()).getSource().getRecordset().stop();
523
                        if (lyr.isJoined()){
524
                                lyr.getRecordset().stop();
525
                        }
526
                        //CHEMA
527

    
528
                        long t2 = System.currentTimeMillis();
529
                        // logger.debug("adapter.stop()");
530
                        adapter.stop();
531
                        lyr.afterPrinting();
532
                        // System.out.println(t2 - t1);
533
                } catch (DriverIOException e) {
534
                        throw new DriverException(e);
535
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
536
                        throw new DriverException(e);
537
                } catch (DriverException e) {
538
                        throw new DriverException(e);
539
                } catch (IOException e) {
540
                        throw new DriverException(e);
541
                }
542

    
543
        }
544

    
545
        public FBitSet queryByShape(IGeometry g, int relationship)
546
                        throws DriverException, VisitException {
547
                return queryByShape(g, relationship, null);
548
        }
549

    
550
        /*
551
         * (non-Javadoc)
552
         *
553
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByShape(com.iver.cit.gvsig.fmap.core.IGeometry,
554
         *      int)
555
         */
556
        public FBitSet queryByShape(IGeometry g, int relationship,
557
                        CancellableMonitorable cancel) throws DriverException,
558
                        VisitException {
559
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
560
                FLyrVect lyr = (FLyrVect) capa;
561
                // if (lyr.getSpatialIndex() == null) AZABALA
562
                if (lyr.getISpatialIndex() == null)
563
                        return super.queryByShape(g, relationship, null);
564

    
565
                long t1 = System.currentTimeMillis();
566
                ReadableVectorial va = lyr.getSource();
567
                ICoordTrans ct = lyr.getCoordTrans();
568
                Rectangle2D bounds = g.getBounds2D();
569
                List lstRecs = lyr.getISpatialIndex().query(bounds);
570
                Integer idRec;
571
                FBitSet bitset = new FBitSet();
572
                Geometry jtsShape = g.toJTSGeometry();
573
                IntersectionMatrix m;
574
                int index;
575
                try {
576
                        va.start();
577

    
578
                        for (int i = 0; i < lstRecs.size(); i++) {
579
                                if (cancel != null) {
580
                                        cancel.reportStep();
581
                                        if (cancel.isCanceled()) {
582
                                                break;
583
                                        }
584
                                }
585
                                idRec = (Integer) lstRecs.get(i);
586
                                index = idRec.intValue();
587
                                IGeometry geom = va.getShape(index);
588
                                if (geom == null)
589
                                        continue;
590
                                if (ct != null) {
591
                                        geom.reProject(ct);
592
                                }
593
                                Geometry jtsGeom = geom.toJTSGeometry();
594
                                switch (relationship) {
595
                                case CONTAINS:
596
                                        m = jtsShape.relate(jtsGeom);
597
                                        if (m.isContains()) {
598
                                                bitset.set(index, true);
599
                                        }
600
                                        break;
601

    
602
                                case CROSSES:
603
                                        m = jtsShape.relate(jtsGeom);
604
                                        if (m.isCrosses(jtsGeom.getDimension(), jtsShape
605
                                                        .getDimension())) {
606
                                                bitset.set(index, true);
607
                                        }
608
                                        break;
609

    
610
                                case DISJOINT:
611
                                        // TODO: CREO QUE EL DISJOINT NO SE PUEDE METER AQUI
612
                                        m = jtsShape.relate(jtsGeom);
613
                                        if (m.isDisjoint()) {
614
                                                bitset.set(index, true);
615
                                        }
616
                                        break;
617

    
618
                                case EQUALS:
619
                                        m = jtsShape.relate(jtsGeom);
620
                                        if (m.isEquals(jtsGeom.getDimension(), jtsShape
621
                                                        .getDimension())) {
622
                                                bitset.set(index, true);
623
                                        }
624
                                        break;
625

    
626
                                case INTERSECTS:
627
                                        m = jtsShape.relate(jtsGeom);
628
                                        if (m.isIntersects()) {
629
                                                bitset.set(index, true);
630
                                        }
631
                                        break;
632

    
633
                                case OVERLAPS:
634
                                        m = jtsShape.relate(jtsGeom);
635
                                        if (m.isOverlaps(jtsGeom.getDimension(), jtsShape
636
                                                        .getDimension())) {
637
                                                bitset.set(index, true);
638
                                        }
639

    
640
                                        break;
641

    
642
                                case TOUCHES:
643
                                        m = jtsShape.relate(jtsGeom);
644
                                        if (m.isTouches(jtsGeom.getDimension(), jtsShape
645
                                                        .getDimension())) {
646
                                                bitset.set(index, true);
647
                                        }
648

    
649
                                        break;
650

    
651
                                case WITHIN:
652
                                        m = jtsShape.relate(jtsGeom);
653
                                        if (m.isWithin()) {
654
                                                bitset.set(index, true);
655
                                        }
656

    
657
                                        break;
658
                                }
659
                        }
660
                        va.stop();
661
                } catch (DriverIOException e) {
662
                        // TODO Auto-generated catch block
663
                        e.printStackTrace();
664
                }
665
                long t2 = System.currentTimeMillis();
666
                // logger.info("queryByShape optimizado sobre la capa " + lyr.getName()
667
                // + ". " + (t2 - t1) + " mseg.");
668
                return bitset;
669
        }
670

    
671
        public FBitSet queryByRect(Rectangle2D rect, CancellableMonitorable cancel)
672
                        throws DriverException {
673
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
674
                FLyrVect lyr = (FLyrVect) capa;
675
                if (lyr.getISpatialIndex() == null)
676
                        return super.queryByRect(rect, cancel);
677

    
678
                ReadableVectorial va = lyr.getSource();
679
                ICoordTrans ct = lyr.getCoordTrans();
680
                Rectangle2D bounds = rect;
681
                List lstRecs = lyr.getISpatialIndex().query(bounds);
682
                Integer idRec;
683
                FBitSet bitset = new FBitSet();
684
                int index;
685
                try {
686
                        va.start();
687
                        DriverAttributes attr = va.getDriverAttributes();
688
                        boolean bMustClone = false;
689
                        if (attr != null) {
690
                                if (attr.isLoadedInMemory()) {
691
                                        bMustClone = attr.isLoadedInMemory();
692
                                }
693
                        }
694

    
695
                        for (int i = 0; i < lstRecs.size(); i++) {
696
                                if (cancel != null) {
697
                                        cancel.reportStep();
698
                                        if (cancel.isCanceled()) {
699
                                                va.stop();
700
                                                return bitset;
701
                                        }
702
                                }
703
                                idRec = (Integer) lstRecs.get(i);
704
                                index = idRec.intValue();
705
                                IGeometry geom = va.getShape(index);
706
                                if (geom == null)// azabala
707
                                        continue;
708
                                if (ct != null) {
709
                                        if (bMustClone)
710
                                                geom = geom.cloneGeometry();
711
                                        geom.reProject(ct);
712
                                }
713
                                if (geom.intersects(rect))
714
                                        bitset.set(index, true);
715
                        }
716
                        va.stop();
717
                } catch (DriverIOException e) {
718
                        // TODO Auto-generated catch block
719
                        e.printStackTrace();
720
                }
721
                return bitset;
722

    
723
        }
724

    
725
        public void process(FeatureVisitor visitor, Rectangle2D rectangle)
726
                        throws DriverException, VisitException {
727
                process(visitor, rectangle, null);
728
        }
729

    
730
        /**
731
         * Processes (by calling visitor.process() method) only those features of
732
         * the vectorial layer associated which intersects given rectangle2d.
733
         *
734
         */
735

    
736
        public void process(FeatureVisitor visitor, Rectangle2D rectangle,
737
                        CancellableMonitorable cancel) throws DriverException,
738
                        VisitException {
739
                if (visitor.start(capa)) {
740
                        FLyrVect lyr = (FLyrVect) capa;
741
                        // if we dont have spatial index or...
742
                        if (lyr.getISpatialIndex() == null) {
743
                                super.process(visitor, rectangle, cancel);
744
                                return;
745
                        }
746
                        // if spatial index is not worthy
747
                        if (!isSpatialIndexNecessary(rectangle)) {
748
                                super.process(visitor, rectangle, cancel);
749
                                return;
750
                        }
751

    
752
                        ReadableVectorial va = lyr.getSource();
753
                        ICoordTrans ct = lyr.getCoordTrans();
754
                        Rectangle2D bounds = rectangle;
755
                        List lstRecs = lyr.getISpatialIndex().query(bounds);
756
                        Integer idRec;
757
                        int index;
758
                        try {
759
                                va.start();
760
                                DriverAttributes attr = va.getDriverAttributes();
761
                                boolean bMustClone = false;
762
                                if (attr != null) {
763
                                        if (attr.isLoadedInMemory()) {
764
                                                bMustClone = attr.isLoadedInMemory();
765
                                        }
766
                                }
767

    
768
                                for (int i = 0; i < lstRecs.size(); i++) {
769
                                        if (cancel != null) {
770
                                                cancel.reportStep();
771
                                        }
772
                                        if (verifyCancelation(cancel, va, visitor))
773
                                                return;
774
                                        idRec = (Integer) lstRecs.get(i);
775
                                        index = idRec.intValue();
776
                                        IGeometry geom = va.getShape(index);
777
                                        if (geom == null)// azabala
778
                                                continue;
779
                                        if (ct != null) {
780
                                                if (bMustClone)
781
                                                        geom = geom.cloneGeometry();
782
                                                geom.reProject(ct);
783
                                        }
784
                                        if (geom.intersects(rectangle))
785
                                                visitor.visit(geom, index);
786
                                }// for
787
                                va.stop();
788
                        } catch (DriverIOException e) {
789
                                // TODO Auto-generated catch block
790
                                e.printStackTrace();
791
                        }
792
                }// if visitor.start
793
        }
794

    
795
        /*
796
         * (non-Javadoc)
797
         *
798
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByPoint(java.awt.geom.Point2D,
799
         *      double)
800
         */
801
        public FBitSet queryByPoint(Point2D p, double tolerance,
802
                        CancellableMonitorable cancel) throws DriverException {
803
                // TODO: OJO!!!!. Est? implementado como un rectangulo.
804
                // Lo correcto deber?a ser calculando las distancias reales
805
                // es decir, con un c?rculo.
806
                Rectangle2D recPoint = new Rectangle2D.Double(p.getX()
807
                                - (tolerance / 2), p.getY() - (tolerance / 2), tolerance,
808
                                tolerance);
809
                return queryByRect(recPoint, cancel);
810
        }
811
}