Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / operations / strategies / ShpStrategy.java @ 3601

History | View | Annotate | Download (19.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 org.apache.log4j.Logger;
52
import org.cresques.cts.ICoordTrans;
53
import org.geotools.resources.geometry.XRectangle2D;
54

    
55
import com.iver.cit.gvsig.fmap.DriverException;
56
import com.iver.cit.gvsig.fmap.ViewPort;
57
import com.iver.cit.gvsig.fmap.core.FShape;
58
import com.iver.cit.gvsig.fmap.core.IGeometry;
59
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
60
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
61
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
62
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
63
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
64
import com.iver.cit.gvsig.fmap.layers.FBitSet;
65
import com.iver.cit.gvsig.fmap.layers.FLayer;
66
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
67
import com.iver.cit.gvsig.fmap.layers.VectorialAdapter;
68
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
69
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
70
import com.iver.cit.gvsig.fmap.layers.layerOperations.Selectable;
71
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
72
import com.iver.cit.gvsig.fmap.operations.Cancellable;
73
import com.iver.cit.gvsig.fmap.rendering.ClassifiedLegendInfo;
74
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
75
import com.iver.cit.gvsig.fmap.rendering.styling.FStyle2D;
76
import com.vividsolutions.jts.geom.Coordinate;
77
import com.vividsolutions.jts.geom.Envelope;
78
import com.vividsolutions.jts.geom.Geometry;
79
import com.vividsolutions.jts.geom.IntersectionMatrix;
80

    
81

    
82
/**
83
 * Esta clase definir? las operaciones de la interfaz FLyrVect de la manera m?s
84
 * ?ptima para los ficheros shp.
85
 */
86
public class ShpStrategy extends DefaultStrategy {
87
        private static Logger logger = Logger.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, FStyle2D)
101
         */
102
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
103
                Cancellable cancel) throws DriverException {
104
                try {
105
                        VectorialAdapter adapter = ((SingleLayer) getCapa()).getSource();
106
                        if (adapter.getShapeCount() <= 0)
107
                        {
108
                            logger.debug("Layer:" + getCapa().getName() + " sin registros");
109
                            return;
110
                        }
111
                        Selectable selection = (Selectable) getCapa();
112
            FLyrVect lyr = (FLyrVect) getCapa();
113
                        ICoordTrans ct = getCapa().getCoordTrans();
114
                        BitSet bitSet = selection.getSelection();
115
                        BoundedShapes shapeBounds = (BoundedShapes) adapter.getDriver();
116
                        // VectorialFileDriver driver = (VectorialFileDriver) adapter.getDriver();
117
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
118
                        adapter.start();
119
                        IGeometry geom;
120
                        if (adapter.getShapeCount()>0){
121
                        geom = adapter.getShape(0);
122
                        }
123
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa()).getLegend();
124

    
125
                        if (l instanceof ClassifiedLegendInfo) {
126
                                ClassifiedLegendInfo clsfLegend = (ClassifiedLegendInfo) l;
127
                                FSymbol[] symbs = clsfLegend.getSymbols();
128
                                //double rSym = 0;
129
                                //double maxRSym = -1;
130

    
131
                                for (int i = 0; i < symbs.length; i++) {
132
                                        // TODO: REVISAR LOS SIMBOLOS Y SUS TAMA?OS
133

    
134
                                        /* Style2D pointSymbol = symbs[i].getPointStyle2D();
135
                                           if (pointSymbol instanceof MarkStyle2D)
136
                                           {
137
                                                   MarkStyle2D mrk2D = (MarkStyle2D) pointSymbol;
138
                                                   rSym = viewPort.toMapDistance(mrk2D.getSize());
139
                                                   if (maxRSym < rSym)
140
                                                           maxRSym = rSym;
141
                                           }*/
142
                                }
143
                        }
144

    
145
                        Rectangle2D extent = viewPort.getAdjustedExtent();
146
                        //AffineTransform at = viewPort.getAffineTransform();
147

    
148
                        int sc;
149

    
150
                        Rectangle2D bounds;
151

    
152
                        
153

    
154
                        long t1 = System.currentTimeMillis();
155
                        // logger.debug("getCapa().getRecordset().start()");
156
                        ((AlphanumericData) getCapa()).getRecordset().start();
157
                        
158
                        // TODO: A revisar si es o no conveniente este sistema
159
                        // de comunicaci?n con los drivers.
160
                        DriverAttributes attr = adapter.getDriverAttributes();
161
                        boolean bMustClone = false;
162
                        if (attr != null)
163
                        {
164
                            if (attr.isLoadedInMemory())
165
                            {
166
                                bMustClone = attr.isLoadedInMemory();                            
167
                            }
168
                        }
169
            
170
            List lstIndexes = null;
171
            
172
            // If area of needed extent is less than fullExtent / 4,
173
            // it will be worthy to use SpatialIndex.
174
            // Otherwhise, we will not use it.
175
                        boolean bUseSpatialIndex = false;
176
            sc = adapter.getShapeCount();
177
            if (lyr.getSpatialIndex() != null)
178
            {
179
                double areaExtent = extent.getWidth() * extent.getHeight();
180
                double areaFullExtent = lyr.getFullExtent().getWidth() * 
181
                                                lyr.getFullExtent().getHeight();
182
                if (areaExtent < (areaFullExtent / 4.0))
183
                {
184
                    Coordinate c1 = new Coordinate(extent.getMinX(), extent.getMinY());
185
                    Coordinate c2 = new Coordinate(extent.getMaxX(), extent.getMaxY());
186
                    Envelope env = new Envelope(c1, c2);
187
                    lstIndexes = lyr.getSpatialIndex().query(env);
188
                    sc = lstIndexes.size();
189
                    bUseSpatialIndex = true;
190
                }
191
            }
192
            int i;
193
            
194
                        for (int aux = 0; aux < sc; aux++) {
195
                                // Salimos si alguien cancela
196
                                if (cancel.isCanceled()) {
197
                                        break;
198
                                }
199
                if (bUseSpatialIndex)
200
                {
201
                    Integer idRec = (Integer) lstIndexes.get(aux);
202
                    i = idRec.intValue();
203
                }
204
                else
205
                {
206
                    i = aux;
207
                }
208
                
209
                                bounds = shapeBounds.getShapeBounds(i);
210

    
211
                                if (ct != null) {
212
                                        bounds = ct.convert(bounds);
213
                                }
214

    
215
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
216
                                        FSymbol symbol = l.getSymbol(i);
217

    
218
                                        if (bitSet.get(i)) {
219
                                                symbol = FSymbol.getSymbolForSelection(symbol);
220
                                        } 
221

    
222
                                        boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
223

    
224
                                        if (bPoint ||
225
                                                        ((bounds.getHeight() > viewPort.getDist1pixel()) ||
226
                                                        (bounds.getWidth() > viewPort.getDist1pixel()))) {
227
                                                geom = adapter.getShape(i);
228
                        
229
                        // PRUEBA DE VELOCIDAD
230
                        // geom = ShapeFactory.createPolygon2D(new GeneralPathX(bounds));
231

    
232
                                                if (ct != null) {
233
                                                    if (bMustClone)
234
                                                        geom = geom.cloneGeometry();
235
                                                        geom.reProject(ct);
236
                                                }
237
                        // FJP: CAMBIO: Sabemos que vamos a dibujar sobre una 
238
                        // imagen, con coordenadas enteras, as?
239
                        // que lo tenemos en cuenta.
240
                                                // ANTES: geom.draw(g, viewPort, symbol);
241
                        // AHORA:
242
                        geom.drawInts(g, viewPort, symbol);
243
                        // geom.draw(g, viewPort, symbol);
244
                        
245

    
246
                                        } else {
247
                                                Point2D.Double pOrig = new Point2D.Double(bounds.getMinX(),
248
                                                                bounds.getMinY());
249
                                                Point2D pDest, pDest2;
250

    
251
                                                pDest = viewPort.getAffineTransform().transform(pOrig, null);
252
                        pDest2 = g.getTransform().transform(pDest, null);
253

    
254
                                                int pixX = (int) pDest2.getX();
255
                                                int pixY = (int) pDest2.getY();
256
                                                if (symbol ==null)
257
                                                        continue;
258
                                                if ((pixX > 0) && (pixX < image.getWidth())) {
259
                                                        if ((pixY > 0) && (pixY < image.getHeight())) {
260
                                                                image.setRGB(pixX, pixY, symbol.getRgb());
261
                                                        }
262
                                                }
263
                                        }
264
                                }
265
                        }
266

    
267
                        // logger.debug("getCapa().getRecordset().stop()");
268
                        ((AlphanumericData) getCapa()).getRecordset().stop();
269

    
270
                        long t2 = System.currentTimeMillis();
271
                        // logger.debug("adapter.stop()");
272
                        adapter.stop();
273

    
274
                        // System.out.println(t2 - t1);
275
                } catch (DriverIOException e) {
276
                        throw new DriverException(e);
277
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
278
                        throw new DriverException(e);
279
                } catch (DriverException e) {
280
                        throw new DriverException(e);
281
                } catch (IOException e) {
282
                        throw new DriverException(e);
283
                }
284
        }
285

    
286
        /**
287
         * M?todo utilizado para dibujar sobre el graphics que se pasa como
288
         * par?metro, pensado para utilizarse para imprimir.
289
         *
290
         * @param g Graphics2D
291
         * @param viewPort ViewPort.
292
         * @param cancel
293
         *
294
         * @throws DriverException
295
         */
296
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel)
297
                throws DriverException {
298
                // super.draw(null, g, viewPort, cancel); // Quiero ejecutar el draw del padre, que es el que va sin acelaraci?n!!
299
        try {
300
            VectorialAdapter adapter = ((SingleLayer) getCapa()).getSource();
301
            if (adapter.getShapeCount() <= 0)
302
            {
303
                logger.debug("Layer:" + getCapa().getName() + " sin registros");
304
                return;
305
            }
306
            Selectable selection = (Selectable) getCapa();
307
            ICoordTrans ct = getCapa().getCoordTrans();
308
            BitSet bitSet = selection.getSelection();
309
            BoundedShapes shapeBounds = (BoundedShapes) adapter.getDriver();
310
            VectorialFileDriver driver = (VectorialFileDriver) adapter.getDriver();
311
            // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
312
            adapter.start();
313
            IGeometry geom;
314
            if (adapter.getShapeCount()>0){
315
            geom = adapter.getShape(0);
316
            }
317
            VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa()).getLegend();
318

    
319
            Rectangle2D extent = viewPort.getAdjustedExtent();
320
            //AffineTransform at = viewPort.getAffineTransform();
321

    
322
            int sc;
323

    
324
            Rectangle2D bounds;
325

    
326
            sc = adapter.getShapeCount();
327

    
328
            long t1 = System.currentTimeMillis();
329
            // logger.debug("getCapa().getRecordset().start()");
330
            ((AlphanumericData) getCapa()).getRecordset().start();
331
            
332
            // TODO: A revisar si es o no conveniente este sistema
333
            // de comunicaci?n con los drivers.
334
            DriverAttributes attr = adapter.getDriverAttributes();
335
            boolean bMustClone = false;
336
            if (attr != null)
337
            {
338
                if (attr.isLoadedInMemory())
339
                {
340
                    bMustClone = attr.isLoadedInMemory();               
341
                }
342
            }
343
            
344

    
345
            for (int i = 0; i < sc; i++) {
346

    
347
                bounds = shapeBounds.getShapeBounds(i);
348

    
349
                if (ct != null) {
350
                    bounds = ct.convert(bounds);
351
                }
352

    
353
                if (XRectangle2D.intersectInclusive(extent, bounds)) {
354
                    FSymbol symbol = l.getSymbol(i);
355

    
356
                    if (bitSet.get(i)) {
357
                        symbol = FSymbol.getSymbolForSelection(symbol);
358
                    } 
359

    
360
                    boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
361

    
362
                    geom = driver.getShape(i);
363
                    
364
                    // PRUEBA DE VELOCIDAD
365
                    // geom = ShapeFactory.createPolygon2D(new GeneralPathX(bounds));
366

    
367
                    if (ct != null) {
368
                        if (bMustClone)
369
                            geom = geom.cloneGeometry();
370
                        geom.reProject(ct);
371
                    }
372
                    geom.draw(g, viewPort, symbol);
373
                }
374
            }
375

    
376
            // logger.debug("getCapa().getRecordset().stop()");
377
            ((AlphanumericData) getCapa()).getRecordset().stop();
378

    
379
            long t2 = System.currentTimeMillis();
380
            // logger.debug("adapter.stop()");
381
            adapter.stop();
382

    
383
            // System.out.println(t2 - t1);
384
        } catch (DriverIOException e) {
385
            throw new DriverException(e);
386
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
387
            throw new DriverException(e);
388
        } catch (DriverException e) {
389
            throw new DriverException(e);
390
        } catch (IOException e) {
391
            throw new DriverException(e);
392
        }
393
        
394
        }
395
    
396
    /* (non-Javadoc)
397
     * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByShape(com.iver.cit.gvsig.fmap.core.IGeometry, int)
398
     */
399
    public FBitSet queryByShape(IGeometry g, int relationship)
400
    throws DriverException, VisitException {
401
        // Si hay un ?ndice espacial, lo usamos para hacer el query.
402
        FLyrVect lyr = (FLyrVect) capa;
403
        if (lyr.getSpatialIndex() == null)
404
            return super.queryByShape(g, relationship);
405
        
406
        long t1 = System.currentTimeMillis();
407
        VectorialAdapter va = lyr.getSource();
408
        ICoordTrans ct = lyr.getCoordTrans();
409
        Rectangle2D bounds = g.getBounds2D();
410
        Coordinate c1 = new Coordinate(bounds.getMinX(), bounds.getMinY());
411
        Coordinate c2 = new Coordinate(bounds.getMaxX(), bounds.getMaxY());
412
        Envelope env = new Envelope(c1, c2);
413
        
414
        List lstRecs = lyr.getSpatialIndex().query(env);
415
        Integer idRec;
416
        FBitSet bitset = new FBitSet();
417
        Geometry jtsShape = g.toJTSGeometry();
418
        IntersectionMatrix m;
419
        int index;
420
        try {
421
            va.start();
422

    
423
            for (int i=0; i < lstRecs.size(); i++)
424
            {
425
                idRec = (Integer) lstRecs.get(i);
426
                index = idRec.intValue();
427
                IGeometry geom = va.getShape(index);
428
                if (ct != null) {
429
                    geom.reProject(ct);
430
                }                
431
                Geometry jtsGeom = geom.toJTSGeometry();
432
                switch (relationship) {
433
                case CONTAINS:
434
                    m = jtsShape.relate(jtsGeom);
435
                    if (m.isContains()) {
436
                        bitset.set(index, true);
437
                    }
438
                    break;
439

    
440
                case CROSSES:
441
                    m = jtsShape.relate(jtsGeom);
442
                    if (m.isCrosses(jtsGeom.getDimension(), jtsShape.getDimension())) {
443
                        bitset.set(index, true);
444
                    }
445
                    break;
446

    
447
                case DISJOINT:
448
                    // TODO: CREO QUE EL DISJOINT NO SE PUEDE METER AQUI
449
                    m = jtsShape.relate(jtsGeom);            
450
                    if (m.isDisjoint()) {
451
                        bitset.set(index, true);
452
                    }
453
                    break;
454

    
455
                case EQUALS:
456
                    m = jtsShape.relate(jtsGeom); 
457
                    if (m.isEquals(jtsGeom.getDimension(), jtsShape.getDimension())) {
458
                        bitset.set(index, true);
459
                    }
460
                    break;
461

    
462
                case INTERSECTS:
463
                    m = jtsShape.relate(jtsGeom);
464
                    if (m.isIntersects()) {
465
                        bitset.set(index, true);
466
                    }
467
                    break;
468

    
469
                case OVERLAPS:
470
                    m = jtsShape.relate(jtsGeom);
471
                    if (m.isOverlaps(jtsGeom.getDimension(), jtsShape.getDimension()))
472
                    {
473
                        bitset.set(index, true);
474
                    }
475

    
476
                    break;
477

    
478
                case TOUCHES:
479
                    m = jtsShape.relate(jtsGeom);
480
                    if (m.isTouches(jtsGeom.getDimension(), jtsShape.getDimension()))
481
                    {
482
                        bitset.set(index, true);
483
                    }
484

    
485
                    break;
486

    
487
                case WITHIN:
488
                    m = jtsShape.relate(jtsGeom);
489
                    if (m.isWithin()) {
490
                        bitset.set(index, true);
491
                    }
492

    
493
                    break;
494
                }
495
            }
496
            va.stop();
497
        } catch (DriverIOException e) {
498
            // TODO Auto-generated catch block
499
            e.printStackTrace();
500
        }
501
        long t2 = System.currentTimeMillis();
502
        logger.debug("queryByShape optimizado sobre la capa " + lyr.getName() + ". " + (t2-t1) + " mseg.");
503
        return bitset;
504
    }
505
    public FBitSet queryByRect(Rectangle2D rect) throws DriverException {
506
        // Si hay un ?ndice espacial, lo usamos para hacer el query.
507
        FLyrVect lyr = (FLyrVect) capa;
508
        if (lyr.getSpatialIndex() == null)
509
            return super.queryByRect(rect);
510

    
511
        VectorialAdapter va = lyr.getSource();
512
        ICoordTrans ct = lyr.getCoordTrans();
513
        Rectangle2D bounds = rect;
514
        Coordinate c1 = new Coordinate(bounds.getMinX(), bounds.getMinY());
515
        Coordinate c2 = new Coordinate(bounds.getMaxX(), bounds.getMaxY());
516
        Envelope env = new Envelope(c1, c2);
517
        
518
        List lstRecs = lyr.getSpatialIndex().query(env);
519
        Integer idRec;
520
        FBitSet bitset = new FBitSet();
521
        int index;
522
        try {
523
            va.start();
524

    
525
            for (int i=0; i < lstRecs.size(); i++)
526
            {
527
                idRec = (Integer) lstRecs.get(i);
528
                index = idRec.intValue();
529
                IGeometry geom = va.getShape(index);
530
                if (ct != null) {
531
                    geom.reProject(ct);
532
                }
533
                if (geom.intersects(rect))
534
                    bitset.set(index, true);
535
            }
536
            va.stop();
537
        } catch (DriverIOException e) {
538
            // TODO Auto-generated catch block
539
            e.printStackTrace();
540
        }
541
        return bitset;
542

    
543
    }
544
    
545
    /* (non-Javadoc)
546
     * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByPoint(java.awt.geom.Point2D, double)
547
     */
548
    public FBitSet queryByPoint(Point2D p, double tolerance)
549
    throws DriverException {
550
        // TODO: OJO!!!!. Est? implementado como un rectangulo.
551
        // Lo correcto deber?a ser calculando las distancias reales
552
        // es decir, con un c?rculo.
553
        Rectangle2D recPoint = new Rectangle2D.Double(p.getX() - (tolerance / 2),
554
                p.getY() - (tolerance / 2), tolerance, tolerance);
555
        return queryByRect(recPoint);
556
    }
557
}