Statistics
| Revision:

root / trunk / extensions / extGeoProcessing / src / com / iver / cit / gvsig / geoprocess / impl / dissolve / fmap / AdjacencyDissolveVisitor.java @ 13881

History | View | Annotate | Download (10.9 KB)

1
/*
2
 * Created on 09-may-2006
3
 *
4
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
5
 *
6
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
21
 *
22
 * For more information, contact:
23
 *
24
 *  Generalitat Valenciana
25
 *   Conselleria d'Infraestructures i Transport
26
 *   Av. Blasco Ib??ez, 50
27
 *   46010 VALENCIA
28
 *   SPAIN
29
 *
30
 *      +34 963862235
31
 *   gvsig@gva.es
32
 *      www.gvsig.gva.es
33
 *
34
 *    or
35
 *
36
 *   IVER T.I. S.A
37
 *   Salamanca 50
38
 *   46005 Valencia
39
 *   Spain
40
 *
41
 *   +34 963163400
42
 *   dac@iver.es
43
 */
44
/* CVS MESSAGES:
45
 *
46
 * $Id: AdjacencyDissolveVisitor.java 13881 2007-09-19 16:22:04Z jaume $
47
 * $Log$
48
 * Revision 1.5  2007-09-19 16:06:59  jaume
49
 * removed unnecessary imports
50
 *
51
 * Revision 1.4  2007/08/07 16:06:04  azabala
52
 * centrilizing JTS in JTSFacade and allowing all geometry types (not only Polygon)
53
 *
54
 * Revision 1.3  2007/03/06 16:47:58  caballero
55
 * Exceptions
56
 *
57
 * Revision 1.2  2006/07/21 11:06:06  azabala
58
 * fixed bug 604: empty dist field in buffered dissolved features
59
 *
60
 * Revision 1.1  2006/06/20 18:20:45  azabala
61
 * first version in cvs
62
 *
63
 * Revision 1.1  2006/05/24 21:11:14  azabala
64
 * primera version en cvs despues de refactoring orientado a crear un framework extensible de geoprocessing
65
 *
66
 *
67
 */
68
package com.iver.cit.gvsig.geoprocess.impl.dissolve.fmap;
69

    
70
import java.awt.geom.Rectangle2D;
71
import java.util.List;
72
import java.util.Stack;
73

    
74
import org.cresques.cts.ICoordTrans;
75

    
76
import com.hardcode.gdbms.driver.exceptions.InitializeDriverException;
77
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
78
import com.hardcode.gdbms.engine.data.driver.DriverException;
79
import com.hardcode.gdbms.engine.values.DoubleValue;
80
import com.hardcode.gdbms.engine.values.Value;
81
import com.hardcode.gdbms.engine.values.ValueFactory;
82
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
83
import com.iver.cit.gvsig.exceptions.visitors.ProcessVisitorException;
84
import com.iver.cit.gvsig.exceptions.visitors.StartVisitorException;
85
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
86
import com.iver.cit.gvsig.fmap.core.IGeometry;
87
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
88
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
89
import com.iver.cit.gvsig.geoprocess.core.fmap.FeatureProcessor;
90
import com.iver.utiles.swing.threads.CancellableMonitorable;
91
import com.vividsolutions.jts.geom.Geometry;
92
import com.vividsolutions.jts.geom.GeometryCollection;
93
import com.vividsolutions.jts.geom.GeometryFactory;
94
import com.vividsolutions.jts.geom.PrecisionModel;
95
import com.vividsolutions.jts.precision.EnhancedPrecisionOp;
96
import com.vividsolutions.jts.precision.SimpleGeometryPrecisionReducer;
97

    
98
/**
99
 * <p>
100
 * This Visitor generates a dissolve of input layer based in adjacency criteria:
101
 * it dissolves two polygons, if and only if they are adjacent.
102
 * </p>
103
 * TODO: To dissolve buffers from radial rings create a DissolveVisitor
104
 * to compare FROM-TO Fields.
105
 *
106
 * @author azabala
107
 *
108
 */
109
public class AdjacencyDissolveVisitor extends DissolveVisitor {
110

    
111
        /**
112
         * Reference to the buffer distance of the visited buffered feature.
113
         */
114
        private DoubleValue currentBufferDistance = null;
115

    
116
        /**
117
         * FIXME REFACTOR THIS!!!!
118
         * This is a workaround to avoid the use of strategies
119
         * and allow the cancelation
120
         * 
121
         * To optimize disolution of buffers, we need to avoid the reading
122
         * of geometries that also has been processed. Strategies cant do this
123
         * 
124
         */
125
        CancellableMonitorable cancelMonitor = null;
126
        
127
//        FIXME Probe to optimize the union of the features 
128
        //(buffer + dissolve when applies to almost all features of the layer
129
        //is very inefficient
130
        private Geometry geometry;
131
        public AdjacencyDissolveVisitor(String dissolveField,
132
                        FeatureProcessor processor) {
133
                super(dissolveField, processor);
134
        }
135

    
136
        //FIXME REFACTOR THIS!!!
137
        public void setCancelMonitor(CancellableMonitorable cancelMonitor){
138
                this.cancelMonitor = cancelMonitor;
139
        }
140
        protected boolean verifyIfDissolve(DissolvedFeature f1, DissolvedFeature f2) {
141
                Geometry geo1 = f1.getJtsGeometry();
142
                Geometry geo2 = f2.getJtsGeometry();
143
                return geo1.intersects(geo2);
144
        }
145

    
146
        /**
147
         * Creates a new IFeature with util info for dissolve geoprocess
148
         * (it ignore non numerical values, etc)
149
         *
150
         * @param g
151
         * @param index
152
         * @return
153
         * @throws DriverException
154
         */
155
        protected DissolvedFeature createFeature(IGeometry g, int index) {
156
                DissolvedFeature solution = new DissolvedFeature(g, null, index);
157
                return solution;
158
        }
159

    
160
        /**
161
         * We overwrite this method because we are not interested in save sumarization
162
         * function values with dissolved features.
163
         * Instead, we want to add buffer distance like an attribute of them.
164
         */
165
        public void visit(IGeometry g, int index) throws VisitorException, ProcessVisitorException {
166
                if(g == null)
167
                        return;
168
//                if(g.getGeometryType() != XTypes.POLYGON &&
169
//                                g.getGeometryType() != XTypes.MULTI)
170
//                        return;
171
                if (!dissolvedGeometries.get(index)) {
172
                        try {
173
                                int fieldIndex = recordset.getFieldIndexByName("DIST");
174
                                currentBufferDistance = (DoubleValue) recordset.getFieldValue(index, fieldIndex);
175
                                // if we havent dissolved this feature
176
                                Stack toDissol = new Stack();// stack for adjacent features
177
                                DissolvedFeature feature = createFeature(g, index);
178
                                toDissol.push(feature);
179
//                                ArrayList geometries = new ArrayList();
180
                                Value[] values = dissolveGeometries(toDissol);
181
//                                Geometry geometry = union(geometries);
182
                                Value[] valuesWithFID = new Value[values.length + 1];
183
                                System.arraycopy(values, 0, valuesWithFID, 1, values.length);
184
                                valuesWithFID[0] = ValueFactory.createValue(fid);
185
                                DissolvedFeature dissolved = new DissolvedFeature(null,valuesWithFID, fid/*index*/);
186
                                dissolved.setJtsGeometry(geometry);
187
                                this.featureProcessor.processFeature(dissolved);
188
                                fid++;
189
                                resetFunctions();
190
                                geometry = null;
191
                        } catch (ReadDriverException e) {
192
                                throw new ProcessVisitorException(recordset.getName(),e,
193
                                        "Error al procesar las geometrias a fusionar durante dissolve");
194
                        } catch (VisitorException e) {
195
                                throw new ProcessVisitorException(recordset.getName(),e,
196
                                "Error al procesar las geometrias a fusionar durante dissolve");
197
                        }
198
                }// ifponer aqui geometry a null?
199
        }
200

    
201
        /**
202
         * We overwrite this method to ignore sumarization values and to
203
         * add buffer distance to the attributes of the result features.
204
         * @throws VisitorException
205
         * @throws ExpansionFileReadException
206
         * @throws ReadDriverException
207
         */
208
        protected Value[] dissolveGeometries(Stack toDissol) throws
209
                        ReadDriverException, ExpansionFileReadException, VisitorException {
210

    
211
                IndividualGeometryDissolveVisitor visitor = null;
212
                DissolvedFeature feature = null;
213
                while (toDissol.size() != 0) {
214
                        feature = (DissolvedFeature) toDissol.pop();
215
                        // flags this idx (to not to process in future)
216
                        dissolvedGeometries.set(feature.getIndex());
217
                        if (visitor == null) {
218
                                visitor = new IndividualGeometryDissolveVisitor(feature,
219
                                                dissolvedGeometries, toDissol,
220
                                                numericField_sumarizeFunction);
221
                                visitor.setDissolveField(this.dissolveField);
222
                        } else {
223
                                visitor.setProcessedFeature(feature);
224
                        }
225
                        Rectangle2D bounds = feature.getGeometry().getBounds2D();
226
                        double xmin = bounds.getMinX();
227
                        double ymin = bounds.getMinY();
228
                        double xmax = bounds.getMaxX();
229
                        double ymax = bounds.getMaxY();
230
                        double magnify = 15d;
231
                        Rectangle2D query = new Rectangle2D.Double(xmin - magnify, ymin
232
                                        - magnify, (xmax - xmin) + magnify, (ymax - ymin) + magnify);
233

    
234
                        if (dissolvedLayer.getISpatialIndex() == null) {
235
                                strategy.process(visitor, query);
236
                        }else{
237
                                process(visitor, query);
238
                        }        
239
                        //al final de toda la pila de llamadas recursivas,
240
                        //geometries tendr? todas las geometrias que debemos dissolver
241
//                        geometries.add(feature.getJtsGeometry());
242
                        if(geometry == null){
243
                                geometry = feature.getJtsGeometry();
244
                        }else{
245
                                GeometryFactory factory = geometry.getFactory();
246
                                Geometry[] geoms = new Geometry[]{geometry, feature.getJtsGeometry()};
247
                                GeometryCollection collection = factory.createGeometryCollection(geoms);
248
//                                geometry = EnhancedPrecisionOp.buffer(collection, 0d);
249
                                
250
                                try{
251
                                        geometry = EnhancedPrecisionOp.buffer(collection, 0d);
252
                                }catch(Throwable t){
253
                                        PrecisionModel precision = new PrecisionModel(1000);
254
                                        //FIXME do a test with TopologyPreservingSimplier and compare
255
                                        SimpleGeometryPrecisionReducer reducer = new SimpleGeometryPrecisionReducer(precision);
256
                                        geometry = reducer.reduce(collection);
257
                                        geometry = EnhancedPrecisionOp.buffer(geometry, 0d);
258
                                }
259
                        }
260
                }// while
261
                Value[] values = new Value[1];
262
                values[0] = currentBufferDistance;
263
                return values;
264
        }
265

    
266
        void process(IndividualGeometryDissolveVisitor visitor, Rectangle2D query){
267
                try {
268
                        if (visitor.start(dissolvedLayer)) {
269
                                ReadableVectorial va = dissolvedLayer.getSource();
270
                                ICoordTrans ct = dissolvedLayer.getCoordTrans();
271
                                List lstRecs = dissolvedLayer.getISpatialIndex().query(query);
272
                                Integer idRec;
273
                                int index;
274
                                        va.start();
275
                                        DriverAttributes attr = va.getDriverAttributes();
276
                                        boolean bMustClone = false;
277
                                        if (attr != null) {
278
                                                if (attr.isLoadedInMemory()) {
279
                                                        bMustClone = attr.isLoadedInMemory();
280
                                                }
281
                                        }
282

    
283
                                        for (int i = 0; i < lstRecs.size(); i++) {
284
                                                if(cancelMonitor != null){
285
                                                        if(cancelMonitor.isCanceled())
286
                                                                return;
287
                                                }
288
                                                idRec = (Integer) lstRecs.get(i);
289
                                                index = idRec.intValue();
290
                                                if(getDissolvedGeometries().get(index))
291
                                                        continue;
292
                                                
293
                                                IGeometry geom = va.getShape(index);
294
                                                if (geom == null)// azabala
295
                                                        continue;
296
                                                if (ct != null) {
297
                                                        if (bMustClone)
298
                                                                geom = geom.cloneGeometry();
299
                                                        geom.reProject(ct);
300
                                                }
301
                                                if (geom.intersects(query))
302
                                                        visitor.visit(geom, index);
303
                                        }// for
304
                                        va.stop();
305
                        }// if visitor.start
306
                        
307
                        visitor.stop(dissolvedLayer);
308
                } catch (StartVisitorException e) {
309
                        // TODO Auto-generated catch block
310
                        e.printStackTrace();
311
                } catch (InitializeDriverException e) {
312
                        // TODO Auto-generated catch block
313
                        e.printStackTrace();
314
                } catch (ExpansionFileReadException e) {
315
                        // TODO Auto-generated catch block
316
                        e.printStackTrace();
317
                } catch (ProcessVisitorException e) {
318
                        // TODO Auto-generated catch block
319
                        e.printStackTrace();
320
                } catch (ReadDriverException e) {
321
                        // TODO Auto-generated catch block
322
                        e.printStackTrace();
323
                } catch (VisitorException e) {
324
                        // TODO Auto-generated catch block
325
                        e.printStackTrace();
326
                }
327
        }
328
        
329
        
330
        
331
        
332

    
333
}