Statistics
| Revision:

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

History | View | Annotate | Download (14 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
        VectorialAdapter va = lyr.getSource();
279
        ICoordTrans ct = lyr.getCoordTrans();
280
        Rectangle2D bounds = g.getBounds2D();
281
        Coordinate c1 = new Coordinate(bounds.getMinX(), bounds.getMinY());
282
        Coordinate c2 = new Coordinate(bounds.getMaxX(), bounds.getMaxY());
283
        Envelope env = new Envelope(c1, c2);
284
        
285
        List lstRecs = lyr.getSpatialIndex().query(env);
286
        Integer idRec;
287
        FBitSet bitset = new FBitSet();
288
        Geometry jtsShape = g.toJTSGeometry();
289
        IntersectionMatrix m;
290
        int index;
291
        try {
292
            va.start();
293

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

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

    
318
                case DISJOINT:
319
                    m = jtsShape.relate(jtsGeom);            
320
                    if (m.isDisjoint()) {
321
                        bitset.set(index, true);
322
                    }
323
                    break;
324

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

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

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

    
346
                    break;
347

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

    
355
                    break;
356

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

    
363
                    break;
364
                }
365
            }
366
            va.stop();
367
        } catch (DriverIOException e) {
368
            // TODO Auto-generated catch block
369
            e.printStackTrace();
370
        }
371
        return bitset;
372
    }
373
    public FBitSet queryByRect(Rectangle2D rect) throws DriverException {
374
        // Si hay un ?ndice espacial, lo usamos para hacer el query.
375
        FLyrVect lyr = (FLyrVect) capa;
376
        if (lyr.getSpatialIndex() == null)
377
            return super.queryByRect(rect);
378

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

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

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