Statistics
| Revision:

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

History | View | Annotate | Download (23.1 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
                                bounds = shapeBounds.getShapeBounds(i);
253
                                if (ct != null) {
254
                                        bounds = ct.convert(bounds);
255
                                }
256
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
257
                                        ISymbol symbol = l.getSymbol(i);
258

    
259
                                        if (bitSet.get(i)) {
260
                                                symbol = symbol.getSymbolForSelection();
261
                                        }
262

    
263
                                        if (symbol == null)
264
                                                continue;
265

    
266
                                        boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
267

    
268
                                        if (bPoint
269
                                                        || ((bounds.getHeight() > viewPort.getDist1pixel()) || (bounds
270
                                                                        .getWidth() > viewPort.getDist1pixel()))) {
271
                                                geom = adapter.getShape(i);
272

    
273
                                                // PRUEBA DE VELOCIDAD
274
                                                // geom = ShapeFactory.createPolygon2D(new
275
                                                // GeneralPathX(bounds));
276

    
277

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

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

    
308
                                        } else {
309
                                                Point2D.Double pOrig = new Point2D.Double(bounds
310
                                                                .getMinX(), bounds.getMinY());
311
                                                Point2D pDest, pDest2;
312

    
313
                                                pDest = viewPort.getAffineTransform().transform(pOrig,
314
                                                                null);
315
                                                pDest2 = g.getTransform().transform(pDest, null);
316

    
317
                                                int pixX = (int) pDest2.getX();
318
                                                int pixY = (int) pDest2.getY();
319
                                                if (symbol == null)
320
                                                        continue;
321
                                                if ((pixX > 0) && (pixX < image.getWidth())) {
322
                                                        if ((pixY > 0) && (pixY < image.getHeight())) {
323
                                                                if (MAC_OS_X) {
324
                                                                        auxBI.setRGB(pixX, pixY, symbol
325
                                                                                        .getOnePointRgb());
326
                                                                } else {
327
                                                                        image.setRGB(pixX, pixY, symbol
328
                                                                                        .getOnePointRgb());
329
                                                                }
330
                                                        }
331
                                                }
332
                                        }
333
                                }
334
                        }
335

    
336
                        if (MAC_OS_X) {
337
                                g.drawImage(auxBI, 0, 0, null);
338
                        }
339

    
340
                        // logger.debug("getCapa().getRecordset().stop()");
341
                        //CHEMA
342
                        // Cerramos la fuente alfanumerica cuando se ha hecho
343
                        // una operacion de 'join'
344
                        //((FLyrVect) getCapa()).getSource().getRecordset().stop();
345
                        if (lyr.isJoined()){
346
                                lyr.getRecordset().stop();
347
                        }
348
                        //CHEMA
349

    
350
                        long t2 = System.currentTimeMillis();
351
                        // logger.debug("adapter.stop()");
352
                        adapter.stop();
353

    
354
                        // System.out.println(t2 - t1);
355
                } catch (DriverIOException e) {
356
                        throw new DriverException(e);
357
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
358
                        throw new DriverException(e);
359
                } catch (DriverException e) {
360
                        throw new DriverException(e);
361
                } catch (IOException e) {
362
                        throw new DriverException(e);
363
                } catch (DriverLoadException e) {
364
                        // TODO Auto-generated catch block
365
                        e.printStackTrace();
366
                }
367
        }
368

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

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

    
410
                        Rectangle2D extent = viewPort.getAdjustedExtent();
411
                        // AffineTransform at = viewPort.getAffineTransform();
412

    
413
                        int sc;
414

    
415
                        Rectangle2D bounds;
416

    
417
                        sc = adapter.getShapeCount();
418

    
419
                        long t1 = System.currentTimeMillis();
420
                        // logger.debug("getCapa().getRecordset().start()");
421

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

    
437

    
438
                        // TODO: A revisar si es o no conveniente este sistema
439
                        // de comunicaci?n con los drivers.
440
                        DriverAttributes attr = adapter.getDriverAttributes();
441
                        boolean bMustClone = false;
442
                        if (attr != null) {
443
                                if (attr.isLoadedInMemory()) {
444
                                        bMustClone = attr.isLoadedInMemory();
445
                                }
446
                        }
447

    
448
                        List lstIndexes = null;
449

    
450
                        boolean bUseSpatialIndex = false;
451
                        if (lyr.getISpatialIndex() != null) {
452
                                if (isSpatialIndexNecessary(extent)) {
453
                                        lstIndexes = lyr.getISpatialIndex().query(extent);
454
                                        if (ct != null) {
455
                                                Rectangle2D newExtent = ct.getInverted()
456
                                                                .convert(extent);
457
                                                lstIndexes = lyr.getISpatialIndex().query(newExtent);
458
                                        } else {
459
                                                lstIndexes = lyr.getISpatialIndex().query(extent);
460
                                        }
461
                                        sc = lstIndexes.size();
462
                                        bUseSpatialIndex = true;
463
                                }// if
464
                        }// if
465

    
466
                        int i;
467
                        for (int aux = 0; aux < sc; aux++) {
468
                                if (bUseSpatialIndex) {
469
                                        Integer idRec = (Integer) lstIndexes.get(aux);
470
                                        i = idRec.intValue();
471
                                } else {
472
                                        i = aux;
473
                                }
474

    
475
                                bounds = shapeBounds.getShapeBounds(i);
476

    
477
                                if (ct != null) {
478
                                        bounds = ct.convert(bounds);
479
                                }
480

    
481
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
482
                                        ISymbol symbol = l.getSymbol(i);
483
                                        if (symbol == null)
484
                                                continue;
485
                                        if (bitSet.get(i)) {
486
                                                symbol = symbol.getSymbolForSelection();
487
                                        }
488

    
489
                                        //boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
490

    
491
                                        geom = driver.getShape(i);
492

    
493
                                        // PRUEBA DE VELOCIDAD
494
                                        // geom = ShapeFactory.createPolygon2D(new
495
                                        // GeneralPathX(bounds));
496

    
497
                                        // JMVIVO: Clonamos siempre que sea necesario y no
498
                                        // solo si hay que reproyectar. Porque el FGeometry.draw
499
                                        // va a aplicar la transformacion sobre la geometria original
500
                                        if (bMustClone)
501
                                                geom = geom.cloneGeometry();
502

    
503
                                        if (ct != null) {
504
                                                geom.reProject(ct);
505
                                        }
506

    
507
                                        geom.draw(g, viewPort, symbol);
508

    
509
                                }
510
                        }
511

    
512
                        // logger.debug("getCapa().getRecordset().stop()");
513
                        //CHEMA
514
                        // Cerramos la fuente alfanumerica cuando se ha hecho
515
                        // una operacion de 'join'
516
                        //((FLyrVect) getCapa()).getSource().getRecordset().stop();
517
                        if (lyr.isJoined()){
518
                                lyr.getRecordset().stop();
519
                        }
520
                        //CHEMA
521

    
522
                        long t2 = System.currentTimeMillis();
523
                        // logger.debug("adapter.stop()");
524
                        adapter.stop();
525
                        lyr.afterPrinting();
526
                        // System.out.println(t2 - t1);
527
                } catch (DriverIOException e) {
528
                        throw new DriverException(e);
529
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
530
                        throw new DriverException(e);
531
                } catch (DriverException e) {
532
                        throw new DriverException(e);
533
                } catch (IOException e) {
534
                        throw new DriverException(e);
535
                }
536

    
537
        }
538

    
539
        public FBitSet queryByShape(IGeometry g, int relationship)
540
                        throws DriverException, VisitException {
541
                return queryByShape(g, relationship, null);
542
        }
543

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

    
559
                long t1 = System.currentTimeMillis();
560
                ReadableVectorial va = lyr.getSource();
561
                ICoordTrans ct = lyr.getCoordTrans();
562
                Rectangle2D bounds = g.getBounds2D();
563
                List lstRecs = lyr.getISpatialIndex().query(bounds);
564
                Integer idRec;
565
                FBitSet bitset = new FBitSet();
566
                Geometry jtsShape = g.toJTSGeometry();
567
                IntersectionMatrix m;
568
                int index;
569
                try {
570
                        va.start();
571

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

    
596
                                case CROSSES:
597
                                        m = jtsShape.relate(jtsGeom);
598
                                        if (m.isCrosses(jtsGeom.getDimension(), jtsShape
599
                                                        .getDimension())) {
600
                                                bitset.set(index, true);
601
                                        }
602
                                        break;
603

    
604
                                case DISJOINT:
605
                                        // TODO: CREO QUE EL DISJOINT NO SE PUEDE METER AQUI
606
                                        m = jtsShape.relate(jtsGeom);
607
                                        if (m.isDisjoint()) {
608
                                                bitset.set(index, true);
609
                                        }
610
                                        break;
611

    
612
                                case EQUALS:
613
                                        m = jtsShape.relate(jtsGeom);
614
                                        if (m.isEquals(jtsGeom.getDimension(), jtsShape
615
                                                        .getDimension())) {
616
                                                bitset.set(index, true);
617
                                        }
618
                                        break;
619

    
620
                                case INTERSECTS:
621
                                        m = jtsShape.relate(jtsGeom);
622
                                        if (m.isIntersects()) {
623
                                                bitset.set(index, true);
624
                                        }
625
                                        break;
626

    
627
                                case OVERLAPS:
628
                                        m = jtsShape.relate(jtsGeom);
629
                                        if (m.isOverlaps(jtsGeom.getDimension(), jtsShape
630
                                                        .getDimension())) {
631
                                                bitset.set(index, true);
632
                                        }
633

    
634
                                        break;
635

    
636
                                case TOUCHES:
637
                                        m = jtsShape.relate(jtsGeom);
638
                                        if (m.isTouches(jtsGeom.getDimension(), jtsShape
639
                                                        .getDimension())) {
640
                                                bitset.set(index, true);
641
                                        }
642

    
643
                                        break;
644

    
645
                                case WITHIN:
646
                                        m = jtsShape.relate(jtsGeom);
647
                                        if (m.isWithin()) {
648
                                                bitset.set(index, true);
649
                                        }
650

    
651
                                        break;
652
                                }
653
                        }
654
                        va.stop();
655
                } catch (DriverIOException e) {
656
                        // TODO Auto-generated catch block
657
                        e.printStackTrace();
658
                }
659
                long t2 = System.currentTimeMillis();
660
                // logger.info("queryByShape optimizado sobre la capa " + lyr.getName()
661
                // + ". " + (t2 - t1) + " mseg.");
662
                return bitset;
663
        }
664

    
665
        public FBitSet queryByRect(Rectangle2D rect, CancellableMonitorable cancel)
666
                        throws DriverException {
667
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
668
                FLyrVect lyr = (FLyrVect) capa;
669
                if (lyr.getISpatialIndex() == null)
670
                        return super.queryByRect(rect, cancel);
671

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

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

    
717
        }
718

    
719
        public void process(FeatureVisitor visitor, Rectangle2D rectangle)
720
                        throws DriverException, VisitException {
721
                process(visitor, rectangle, null);
722
        }
723

    
724
        /**
725
         * Processes (by calling visitor.process() method) only those features of
726
         * the vectorial layer associated which intersects given rectangle2d.
727
         *
728
         */
729

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

    
746
                        ReadableVectorial va = lyr.getSource();
747
                        ICoordTrans ct = lyr.getCoordTrans();
748
                        Rectangle2D bounds = rectangle;
749
                        List lstRecs = lyr.getISpatialIndex().query(bounds);
750
                        Integer idRec;
751
                        int index;
752
                        try {
753
                                va.start();
754
                                DriverAttributes attr = va.getDriverAttributes();
755
                                boolean bMustClone = false;
756
                                if (attr != null) {
757
                                        if (attr.isLoadedInMemory()) {
758
                                                bMustClone = attr.isLoadedInMemory();
759
                                        }
760
                                }
761

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

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