Statistics
| Revision:

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

History | View | Annotate | Download (14.3 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
                        ICoordTrans ct = getCapa().getCoordTrans();
113
                        BitSet bitSet = selection.getSelection();
114
                        BoundedShapes shapeBounds = (BoundedShapes) adapter.getDriver();
115
                        VectorialFileDriver driver = (VectorialFileDriver) adapter.getDriver();
116
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
117
                        adapter.start();
118
                        IGeometry geom;
119
                        if (adapter.getShapeCount()>0){
120
                        geom = adapter.getShape(0);
121
                        }
122
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa()).getLegend();
123

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

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

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

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

    
147
                        int sc;
148

    
149
                        Rectangle2D bounds;
150

    
151
                        sc = adapter.getShapeCount();
152

    
153
                        long t1 = System.currentTimeMillis();
154
                        // logger.debug("getCapa().getRecordset().start()");
155
                        ((AlphanumericData) getCapa()).getRecordset().start();
156
                        
157
                        // TODO: A revisar si es o no conveniente este sistema
158
                        // de comunicaci?n con los drivers.
159
                        DriverAttributes attr = adapter.getDriverAttributes();
160
                        boolean bMustClone = false;
161
                        if (attr != null)
162
                        {
163
                            if (attr.isLoadedInMemory())
164
                            {
165
                                bMustClone = attr.isLoadedInMemory();                            
166
                            }
167
                        }
168
                        
169

    
170
                        for (int i = 0; i < sc; i++) {
171
                                // Salimos si alguien cancela
172
                                if (cancel.isCanceled()) {
173
                                        break;
174
                                }
175

    
176
                                bounds = shapeBounds.getShapeBounds(i);
177

    
178
                                if (ct != null) {
179
                                        bounds = ct.convert(bounds);
180
                                }
181

    
182
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
183
                                        FSymbol symbol = l.getSymbol(i);
184

    
185
                                        if (bitSet.get(i)) {
186
                                                symbol = FSymbol.getSymbolForSelection(symbol);
187
                                        } 
188

    
189
                                        boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
190

    
191
                                        if (bPoint ||
192
                                                        ((bounds.getHeight() > viewPort.getDist1pixel()) ||
193
                                                        (bounds.getWidth() > viewPort.getDist1pixel()))) {
194
                                                geom = driver.getShape(i);
195
                        
196
                        // PRUEBA DE VELOCIDAD
197
                        // geom = ShapeFactory.createPolygon2D(new GeneralPathX(bounds));
198

    
199
                                                if (ct != null) {
200
                                                    if (bMustClone)
201
                                                        geom = geom.cloneGeometry();
202
                                                        geom.reProject(ct);
203
                                                }
204
                        // FJP: CAMBIO: Sabemos que vamos a dibujar sobre una 
205
                        // imagen, con coordenadas enteras, as?
206
                        // que lo tenemos en cuenta.
207
                                                // ANTES: geom.draw(g, viewPort, symbol);
208
                        // AHORA:
209
                        geom.drawInts(g, viewPort, symbol);
210
                        // geom.draw(g, viewPort, symbol);
211
                        
212

    
213
                                        } else {
214
                                                Point2D.Double pOrig = new Point2D.Double(bounds.getMinX(),
215
                                                                bounds.getMinY());
216
                                                Point2D pDest, pDest2;
217

    
218
                                                pDest = viewPort.getAffineTransform().transform(pOrig, null);
219
                        pDest2 = g.getTransform().transform(pDest, null);
220

    
221
                                                int pixX = (int) pDest2.getX();
222
                                                int pixY = (int) pDest2.getY();
223
                                                if (symbol ==null)
224
                                                        continue;
225
                                                if ((pixX > 0) && (pixX < image.getWidth())) {
226
                                                        if ((pixY > 0) && (pixY < image.getHeight())) {
227
                                                                image.setRGB(pixX, pixY, symbol.getRgb());
228
                                                        }
229
                                                }
230
                                        }
231
                                }
232
                        }
233

    
234
                        // logger.debug("getCapa().getRecordset().stop()");
235
                        ((AlphanumericData) getCapa()).getRecordset().stop();
236

    
237
                        long t2 = System.currentTimeMillis();
238
                        // logger.debug("adapter.stop()");
239
                        adapter.stop();
240

    
241
                        // System.out.println(t2 - t1);
242
                } catch (DriverIOException e) {
243
                        throw new DriverException(e);
244
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
245
                        throw new DriverException(e);
246
                } catch (DriverException e) {
247
                        throw new DriverException(e);
248
                } catch (IOException e) {
249
                        throw new DriverException(e);
250
                }
251
        }
252

    
253
        /**
254
         * M?todo utilizado para dibujar sobre el graphics que se pasa como
255
         * par?metro, pensado para utilizarse para imprimir.
256
         *
257
         * @param g Graphics2D
258
         * @param viewPort ViewPort.
259
         * @param cancel
260
         *
261
         * @throws DriverException
262
         */
263
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel)
264
                throws DriverException {
265
                super.draw(null, g, viewPort, cancel); // Quiero ejecutar el draw del padre, que es el que va sin acelaraci?n!!
266
        }
267
    
268
    /* (non-Javadoc)
269
     * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByShape(com.iver.cit.gvsig.fmap.core.IGeometry, int)
270
     */
271
    public FBitSet queryByShape(IGeometry g, int relationship)
272
    throws DriverException, VisitException {
273
        // Si hay un ?ndice espacial, lo usamos para hacer el query.
274
        FLyrVect lyr = (FLyrVect) capa;
275
        if (lyr.getSpatialIndex() == null)
276
            return super.queryByShape(g, relationship);
277
        
278
        long t1 = System.currentTimeMillis();
279
        VectorialAdapter va = lyr.getSource();
280
        ICoordTrans ct = lyr.getCoordTrans();
281
        Rectangle2D bounds = g.getBounds2D();
282
        Coordinate c1 = new Coordinate(bounds.getMinX(), bounds.getMinY());
283
        Coordinate c2 = new Coordinate(bounds.getMaxX(), bounds.getMaxY());
284
        Envelope env = new Envelope(c1, c2);
285
        
286
        List lstRecs = lyr.getSpatialIndex().query(env);
287
        Integer idRec;
288
        FBitSet bitset = new FBitSet();
289
        Geometry jtsShape = g.toJTSGeometry();
290
        IntersectionMatrix m;
291
        int index;
292
        try {
293
            va.start();
294

    
295
            for (int i=0; i < lstRecs.size(); i++)
296
            {
297
                idRec = (Integer) lstRecs.get(i);
298
                index = idRec.intValue();
299
                IGeometry geom = va.getShape(index);
300
                if (ct != null) {
301
                    geom.reProject(ct);
302
                }                
303
                Geometry jtsGeom = geom.toJTSGeometry();
304
                switch (relationship) {
305
                case CONTAINS:
306
                    m = jtsShape.relate(jtsGeom);
307
                    if (m.isContains()) {
308
                        bitset.set(index, true);
309
                    }
310
                    break;
311

    
312
                case CROSSES:
313
                    m = jtsShape.relate(jtsGeom);
314
                    if (m.isCrosses(jtsGeom.getDimension(), jtsShape.getDimension())) {
315
                        bitset.set(index, true);
316
                    }
317
                    break;
318

    
319
                case DISJOINT:
320
                    // TODO: CREO QUE EL DISJOINT NO SE PUEDE METER AQUI
321
                    m = jtsShape.relate(jtsGeom);            
322
                    if (m.isDisjoint()) {
323
                        bitset.set(index, true);
324
                    }
325
                    break;
326

    
327
                case EQUALS:
328
                    m = jtsShape.relate(jtsGeom); 
329
                    if (m.isEquals(jtsGeom.getDimension(), jtsShape.getDimension())) {
330
                        bitset.set(index, true);
331
                    }
332
                    break;
333

    
334
                case INTERSECTS:
335
                    m = jtsShape.relate(jtsGeom);
336
                    if (m.isIntersects()) {
337
                        bitset.set(index, true);
338
                    }
339
                    break;
340

    
341
                case OVERLAPS:
342
                    m = jtsShape.relate(jtsGeom);
343
                    if (m.isOverlaps(jtsGeom.getDimension(), jtsShape.getDimension()))
344
                    {
345
                        bitset.set(index, true);
346
                    }
347

    
348
                    break;
349

    
350
                case TOUCHES:
351
                    m = jtsShape.relate(jtsGeom);
352
                    if (m.isTouches(jtsGeom.getDimension(), jtsShape.getDimension()))
353
                    {
354
                        bitset.set(index, true);
355
                    }
356

    
357
                    break;
358

    
359
                case WITHIN:
360
                    m = jtsShape.relate(jtsGeom);
361
                    if (m.isWithin()) {
362
                        bitset.set(index, true);
363
                    }
364

    
365
                    break;
366
                }
367
            }
368
            va.stop();
369
        } catch (DriverIOException e) {
370
            // TODO Auto-generated catch block
371
            e.printStackTrace();
372
        }
373
        long t2 = System.currentTimeMillis();
374
        logger.debug("queryByShape optimizado sobre la capa " + lyr.getName() + ". " + (t2-t1) + " mseg.");
375
        return bitset;
376
    }
377
    public FBitSet queryByRect(Rectangle2D rect) throws DriverException {
378
        // Si hay un ?ndice espacial, lo usamos para hacer el query.
379
        FLyrVect lyr = (FLyrVect) capa;
380
        if (lyr.getSpatialIndex() == null)
381
            return super.queryByRect(rect);
382

    
383
        VectorialAdapter va = lyr.getSource();
384
        ICoordTrans ct = lyr.getCoordTrans();
385
        Rectangle2D bounds = rect;
386
        Coordinate c1 = new Coordinate(bounds.getMinX(), bounds.getMinY());
387
        Coordinate c2 = new Coordinate(bounds.getMaxX(), bounds.getMaxY());
388
        Envelope env = new Envelope(c1, c2);
389
        
390
        List lstRecs = lyr.getSpatialIndex().query(env);
391
        Integer idRec;
392
        FBitSet bitset = new FBitSet();
393
        int index;
394
        try {
395
            va.start();
396

    
397
            for (int i=0; i < lstRecs.size(); i++)
398
            {
399
                idRec = (Integer) lstRecs.get(i);
400
                index = idRec.intValue();
401
                IGeometry geom = va.getShape(index);
402
                if (ct != null) {
403
                    geom.reProject(ct);
404
                }
405
                if (geom.intersects(rect))
406
                    bitset.set(index, true);
407
            }
408
            va.stop();
409
        } catch (DriverIOException e) {
410
            // TODO Auto-generated catch block
411
            e.printStackTrace();
412
        }
413
        return bitset;
414

    
415
    }
416
    
417
    /* (non-Javadoc)
418
     * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByPoint(java.awt.geom.Point2D, double)
419
     */
420
    public FBitSet queryByPoint(Point2D p, double tolerance)
421
    throws DriverException {
422
        // TODO: OJO!!!!. Est? implementado como un rectangulo.
423
        // Lo correcto deber?a ser calculando las distancias reales
424
        // es decir, con un c?rculo.
425
        Rectangle2D recPoint = new Rectangle2D.Double(p.getX() - (tolerance / 2),
426
                p.getY() - (tolerance / 2), tolerance, tolerance);
427
        return queryByRect(recPoint);
428
    }
429
}