Statistics
| Revision:

root / trunk / extensions / extGraph / src / org / gvsig / graph / core / NetworkUtils.java @ 29993

History | View | Annotate | Download (16 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 org.gvsig.graph.core;
42

    
43
import java.awt.Color;
44
import java.awt.geom.Point2D;
45
import java.awt.geom.Rectangle2D;
46
import java.io.File;
47
import java.util.ArrayList;
48
import java.util.Iterator;
49

    
50
import javax.swing.ImageIcon;
51

    
52
import org.gvsig.exceptions.BaseException;
53
import org.gvsig.graph.solvers.Route;
54

    
55
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
56
import com.iver.andami.messages.NotificationManager;
57
import com.iver.cit.gvsig.fmap.MapControl;
58
import com.iver.cit.gvsig.fmap.ViewPort;
59
import com.iver.cit.gvsig.fmap.core.IFeature;
60
import com.iver.cit.gvsig.fmap.core.IGeometry;
61
import com.iver.cit.gvsig.fmap.core.ShapeFactory;
62
import com.iver.cit.gvsig.fmap.core.styles.ArrowDecoratorStyle;
63
import com.iver.cit.gvsig.fmap.core.styles.ILineStyle;
64
import com.iver.cit.gvsig.fmap.core.styles.SimpleLineStyle;
65
import com.iver.cit.gvsig.fmap.core.symbols.IMarkerSymbol;
66
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
67
import com.iver.cit.gvsig.fmap.core.symbols.SimpleLineSymbol;
68
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
69
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
70
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
71
import com.iver.cit.gvsig.fmap.featureiterators.FeatureIteratorTest;
72
import com.iver.cit.gvsig.fmap.layers.FLayer;
73
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
74
import com.iver.cit.gvsig.fmap.layers.GraphicLayer;
75
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
76
import com.iver.cit.gvsig.fmap.layers.VectorialAdapter;
77
import com.iver.cit.gvsig.fmap.rendering.FGraphic;
78

    
79
import com.vividsolutions.jts.geom.Coordinate;
80
import com.vividsolutions.jts.geom.Geometry;
81
import com.vividsolutions.jts.geom.GeometryFactory;
82
import com.vividsolutions.jts.geom.LineString;
83
import com.vividsolutions.jts.geom.MultiPoint;
84
import com.vividsolutions.jts.geom.Point;
85

    
86
public class NetworkUtils {
87
        static int idSymbolFlag = -1;
88

    
89
        static private GeometryFactory geomFactory = new GeometryFactory();
90

    
91
        private static IMarkerSymbol simFlag2;
92
        private static FSymbol simFlag;
93

    
94
        
95
        
96
        public static void clearBarriersFromGraphics(MapControl mc) {
97
                GraphicLayer graphics = mc.getMapContext().getGraphicsLayer();
98
                for (int i = graphics.getNumGraphics() - 1; i >= 0; i--) {
99
                        FGraphic aux = graphics.getGraphic(i);
100
                        if (aux.getTag() != null)
101
                                if (aux.getTag().equalsIgnoreCase("BARRIER"))
102
                                        graphics.removeGraphic(aux);
103
                }
104
        }
105

    
106
        public static void clearFlagsFromGraphics(MapControl mc) {
107
                GraphicLayer graphics = mc.getMapContext().getGraphicsLayer();
108
                for (int i = graphics.getNumGraphics() - 1; i >= 0; i--) {
109
                        FGraphic aux = graphics.getGraphic(i);
110
                        if (aux.getTag() != null)
111
                                if (aux.getTag().equalsIgnoreCase("FLAG"))
112
                                        graphics.removeGraphic(aux);
113
                }
114
        }
115

    
116
        public static void clearFlagFromGraphics(MapControl mc, GvFlag flag) {
117
                GraphicLayer graphics = mc.getMapContext().getGraphicsLayer();
118
                FGraphic graphic = graphics.getGraphicByObjectTag(flag);
119
                graphics.removeGraphic(graphic);
120
        }
121

    
122
        public static void clearRouteFromGraphics(MapControl mc) {
123
                GraphicLayer graphics = mc.getMapContext().getGraphicsLayer();
124
                for (int i = graphics.getNumGraphics() - 1; i >= 0; i--) {
125
                        FGraphic aux = graphics.getGraphic(i);
126
                        if (aux.getTag() != null)
127
                                if (aux.getTag().equalsIgnoreCase("ROUTE"))
128
                                        graphics.removeGraphic(aux);
129
                }
130
        }
131
        
132
        public static void centerGraphicsOnFlags(MapControl mc, GvFlag[] flags){
133
                ViewPort vp = mc.getViewPort();
134
                Rectangle2D extent = vp.getAdjustedExtent();
135
                /*double xNC = flag.getOriginalPoint().getX();
136
                double yNC = flag.getOriginalPoint().getY();*/
137
                double width = extent.getWidth();
138
                double height = extent.getHeight();
139
                
140
                Rectangle2D.Double r = null;//new Rectangle2D.Double();
141
                
142
                /*r.width = width;
143
                r.height = height;
144
                r.x = xNC - width/2;
145
                r.y = yNC - height/2;*/
146
                
147
                for (int i = 0; i < flags.length; i++) {
148
                        if(flags[i]!=null){ 
149
                                Point2D p=flags[i].getOriginalPoint();
150
                                if (r==null)
151
                                        r=new Rectangle2D.Double(p.getX(),p.getY(),0,0);
152
                                else
153
                                        r.add(flags[i].getOriginalPoint());
154
                        }
155
                }
156
                
157
                double realTol = mc.getViewPort().toMapDistance(15);
158
                
159
                r.height=r.height+realTol;
160
                r.width=r.width+realTol;
161
                r.x = r.x-(realTol/2.0);//r.getMaxX() - r.width/2;
162
                r.y = r.y-(realTol/2.0);//r.getMaxY() - r.height/2;
163

    
164
                vp.setExtent(r);
165
                mc.getMapContext().invalidate();
166
        }
167
        
168
        public static void centerGraphicsOnFlag(MapControl mc, GvFlag flag){
169
                ViewPort vp = mc.getViewPort();
170
                Rectangle2D extent = vp.getAdjustedExtent();
171
                double xNC = flag.getOriginalPoint().getX();
172
                double yNC = flag.getOriginalPoint().getY();
173
                double width = extent.getWidth();
174
                double height = extent.getHeight();
175
                
176
                Rectangle2D.Double r = new Rectangle2D.Double();
177
                
178
                r.width = width;
179
                r.height = height;
180
                r.x = xNC - width/2;
181
                r.y = yNC - height/2;
182

    
183
                vp.setExtent(r);
184
        }
185
        
186
        public static void drawRouteOnGraphics(MapControl mc, Route route){
187
                Iterator it = route.getFeatureList().iterator();
188
                int idSymbolLine=-1;
189
                GraphicLayer graphicLayer = mc.getMapContext().getGraphicsLayer();
190
//                if (idSymbolLine == -1)
191
                {
192
                        SimpleLineSymbol arrowSymbol = new SimpleLineSymbol();
193
                        // FSymbol arrowSymbol = new FSymbol(FConstant.SYMBOL_TYPE_LINE);
194
                        arrowSymbol.setLineColor(Color.RED);
195
                        arrowSymbol.setUnit(-1); //pixels
196
                        arrowSymbol.setLineWidth(3.0f);
197
                        ILineStyle lineStyle = new SimpleLineStyle();
198
                        
199
                        ArrowDecoratorStyle arrowDecoratorStyle = new ArrowDecoratorStyle();
200
                        arrowDecoratorStyle.setArrowMarkerCount(1);
201
                        lineStyle.setArrowDecorator(arrowDecoratorStyle );
202
                        lineStyle.setLineWidth(3.0f);
203
                        arrowSymbol.setLineStyle(lineStyle);
204
                        idSymbolLine = graphicLayer.addSymbol(arrowSymbol);
205
                        
206
                }
207
                // Para evitar hacer reallocate de los elementos de la
208
                // graphicList cada vez, creamos primero la lista
209
                // y la insertamos toda de una vez.
210
                ArrayList graphicsRoute = new ArrayList();
211
                while (it.hasNext()) {
212
                        IFeature feat = (IFeature) it.next();
213
                        IGeometry gAux = feat.getGeometry();
214
                        FGraphic graphic = new FGraphic(gAux, idSymbolLine);
215
                        graphic.setTag("ROUTE");
216
                        graphicsRoute.add(graphic);
217
//                        graphicLayer.insertGraphic(0, graphic);
218
                }
219
                // Lo insertamos al principio de la lista para que los
220
                // pushpins se dibujen despu?s.
221

    
222
                graphicLayer.inserGraphics(0, graphicsRoute);
223
                mc.drawGraphics();
224
        }
225

    
226
        public static File getNetworkFile(FLayer lyr) {
227
                String directoryName = System.getProperty("java.io.tmpdir");
228
                String aux = lyr.getName().replaceAll("\\Q.shp\\E", ".net");
229
                File newFile = new File(directoryName + File.separator + aux);
230
                return newFile;
231

    
232
        }
233

    
234
        public static void addGraphicFlag(MapControl mapControl, GvFlag flag) {
235
                addGraphicFlag(mapControl, flag, getDefaultSymbolFlag());
236
        }
237

    
238
        /**
239
         * @return
240
         */
241
        public static ISymbol getDefaultSymbolFlag() {
242
                if (simFlag == null) {
243
                        
244
                        simFlag = new FSymbol(FConstant.SYMBOL_TYPE_ICON);
245
                        ImageIcon icon = new ImageIcon(NetworkUtils.class.getClassLoader()
246
                                        .getResource("images/pushpin.png")); 
247
                        simFlag.setIcon(icon.getImage());
248
                        simFlag.setSize(24);
249
                        simFlag.setSizeInPixels(true);
250
                        simFlag.setStyle(FConstant.SYMBOL_STYLE_MARKER_IMAGEN);
251
                }
252
                return simFlag;
253
        }
254

    
255
        public static void addGraphicFlag(MapControl mapControl, GvFlag flag,
256
                        ISymbol sym) {
257
                GraphicLayer graphicLayer = mapControl.getMapContext()
258
                                .getGraphicsLayer();
259
                int idSymbol = graphicLayer.getSymbol(sym);
260
                if (idSymbol == -1) { // El s?mbolo no existe todav?a en la lista de
261
                                                                // gr?ficos
262
                        idSymbol = graphicLayer.addSymbol(sym);
263
                }
264
                IGeometry gAux = ShapeFactory.createPoint2D(flag.getOriginalPoint()
265
                                .getX(), flag.getOriginalPoint().getY());
266
                FGraphic graphic = new FGraphic(gAux, idSymbol);
267
                graphic.setTag("FLAG");
268
                graphic.setObjectTag(flag);
269
                graphicLayer.addGraphic(graphic);
270

    
271
        }
272

    
273
        /**
274
         * Receives jtsgeom, percentage of desired linestring and direction.
275
         * 
276
         * @param geom
277
         * @param pct
278
         * @param direction
279
         *            1=> same as geometry. 0=> Inversed
280
         * @return partial linestring
281
         */
282
        public static LineString getPartialLineString(Geometry geom, double pct,
283
                        int direction)
284
        // Si parte vale cero, los v?lidos son los primeros. Si no, los segundos.
285
        {
286
                int j, numVertices;
287
                double longAcum, longReal, longBuscada, distSobre, miniPorcentaje;
288
                double nuevaX, nuevaY; // Por cuestiones de claridad al programar
289
                double dist = 0;
290

    
291
                longAcum = 0;
292
                longReal = geom.getLength();
293
                longBuscada = longReal * pct;
294
                Coordinate[] coords = geom.getCoordinates();
295
                Coordinate c1 = null, c2 = null;
296
                ArrayList savedCoords = new ArrayList();
297
                Coordinate lastCoord = null;
298

    
299
                if (direction > 0) // Hemos entrado por el 1 hacia el 2 (al 2 no
300
                                                        // llegamos)
301
                {
302
                        for (j = 0; j < coords.length - 1; j++) {
303
                                c1 = coords[j];
304
                                c2 = coords[j + 1];
305
                                dist = c1.distance(c2);
306
                                longAcum += dist;
307
                                if ((lastCoord ==null) || (!c1.equals2D(lastCoord)))
308
                                {
309
                                        savedCoords.add(c1);
310
                                        lastCoord = c1;
311
                                }
312

    
313
                                if (longAcum >= longBuscada) {
314
                                        // Hasta aqu?. Ahora ahi que poner el punto sobre el tramo
315
                                        distSobre = dist - (longAcum - longBuscada);
316
                                        miniPorcentaje = distSobre / dist;
317

    
318
                                        nuevaX = c1.x + (c2.x - c1.x) * miniPorcentaje;
319
                                        nuevaY = c1.y + (c2.y - c1.y) * miniPorcentaje;
320

    
321
                                        savedCoords.add(new Coordinate(nuevaX, nuevaY));
322
                                        break;
323
                                } // if longAcum >= longBuscada
324
                        } // for j
325

    
326
                } else // Hemos entrado por el 2 hacia el 1
327
                {
328
                        numVertices = 0;
329
                        for (j = 0; j < coords.length; j++) {
330
                                // //////////////////////////////////////////////////////////////
331
                                // 13_ene_2005: Si el ?ltimo punto es el ?ltimo punto no
332
                                // podemos acceder al elemento j+1 porque nos salimos del shape
333
                                // ///////////////////////////////////////////////////////////////
334
                                c1 = coords[j];
335
                                if (j < coords.length - 1) {
336
                                        c2 = coords[j + 1];
337

    
338
                                        dist = c1.distance(c2);
339
                                        longAcum += dist;
340
                                }
341

    
342
                                if (longAcum >= longBuscada) {
343
                                        // Hasta aqu?. Empezamos a meter puntos
344

    
345
                                        if (numVertices == 0) {
346
                                                distSobre = dist - (longAcum - longBuscada);
347
                                                miniPorcentaje = distSobre / dist;
348
                                                nuevaX = c1.x + (c2.x - c1.x) * miniPorcentaje;
349
                                                nuevaY = c1.y + (c2.y - c1.y) * miniPorcentaje;
350

    
351
                                                savedCoords.add(new Coordinate(nuevaX, nuevaY));
352
                                                savedCoords.add(c2);
353
                                        } else {
354
                                                if ((lastCoord ==null) || (!c2.equals2D(lastCoord)))
355
                                                {
356
                                                        savedCoords.add(c2);
357
                                                        lastCoord = c2;
358
                                                }
359

    
360
                                        }
361
                                        numVertices++;
362
                                        // break;
363
                                } // if longAcum >= longBuscada
364
                        } // for j
365

    
366
                        // savedCoords.add(c2);
367

    
368
                } // if else
369

    
370
                return geomFactory.createLineString((Coordinate[]) savedCoords
371
                                .toArray(new Coordinate[0]));
372
        }
373

    
374
        public static double[] string2doubleArray(String str, String separator) throws NumberFormatException{
375
                str=str.replace(" ", "");
376
                
377
                if(!str.contains(separator)){
378
                        try{
379
                                double[] result=new double[1];
380
                                result[0]=Double.parseDouble(str);
381
                                return result;
382
                        }
383
                        catch(NumberFormatException except){
384
                                if(str.startsWith("[") && str.endsWith("]")){
385
                                        String[] tokens=str.substring(1, str.length()-1).split(":");
386
                                        if(tokens.length==3){
387
                                                try{
388
                                                        Double ini=Double.valueOf(tokens[0]);
389
                                                        Double end=Double.valueOf(tokens[1]);
390
                                                        Double interval=Double.valueOf(tokens[2]);
391
                                                        
392
                                                        int length=((int)((end-ini)/interval))+1;
393
                                                        if(length>0){
394
                                                                double[] result=new double[length];
395
                                                                
396
                                                                for (int i = 0; i < result.length; i++) {
397
                                                                        result[i]=ini;
398
                                                                        ini+=interval;
399
                                                                }
400
                                                                
401
                                                                return result;
402
                                                        }
403
                                                        else{
404
                                                                return new double[0];
405
                                                        }
406
                                                }
407
                                                catch(NumberFormatException except2){
408
                                                        throw except2;
409
                                                }
410
                                        }
411
                                        else{
412
                                                throw except;
413
                                        }
414
                                }
415
                                else{
416
                                        throw except;
417
                                }
418
                        }
419
                }
420
                else{
421
                        String[] parts;
422
                        parts = str.split(separator);
423
                        ArrayList ret=new ArrayList();
424

    
425
                        for (int i = 0; i < parts.length; i++) {
426
                                try{
427
                                        ret.add(Double.valueOf(parts[i]));
428
                                }
429
                                catch(NumberFormatException except){
430
                                        if(parts[i].startsWith("[") && parts[i].endsWith("]")){
431
                                                String[] tokens=parts[i].substring(1, parts[i].length()-1).split(":");
432
                                                if(tokens.length==3){
433
                                                        try{
434
                                                                Double ini=Double.valueOf(tokens[0]);
435
                                                                Double end=Double.valueOf(tokens[1]);
436
                                                                Double interval=Double.valueOf(tokens[2]);
437

    
438
                                                                for (double j = ini; j <= end; j+=interval) {
439
                                                                        ret.add(Double.valueOf(j));
440
                                                                }
441
                                                        }
442
                                                        catch(NumberFormatException except2){
443
                                                                throw except2;
444
                                                        }
445
                                                }
446
                                        }
447
                                        else{
448
                                                throw except;
449
                                        }
450
                                }
451
                        }
452

    
453
                        double[] result=new double[ret.size()];
454
                        for (int i = 0; i < result.length; i++) {
455
                                result[i]=((Double)ret.get(i)).doubleValue();
456
                        }
457

    
458
                        return result;
459
                }
460
        }
461

    
462
        /**
463
         * Truco sucio para evitar la inquisici?n. Cuando funcione, habr? que hacer
464
         * una propuesta para ver si es aceptado....
465
         * 
466
         * @param mapCtrl
467
         * @param x
468
         * @param y
469
         */
470
        public static void flashPoint(MapControl mapCtrl, double x, double y) {
471
                flashPoint(mapCtrl, Color.RED, 5, x, y);
472
        }
473
        
474
        
475
        /**
476
         * @param mapCtrl
477
         * @param color
478
         * @param x
479
         * @param y
480
         */
481
        public static void flashPoint(MapControl mapCtrl, Color color, int maxCount, double x, double y){
482
                int delay = 100; // milliseconds
483
                MyTask task = new MyTask(mapCtrl, color, maxCount, x, y);
484

    
485
                java.util.Timer timer = new java.util.Timer();
486
                timer.schedule(task, delay, 60);
487

    
488
        }
489

    
490
        public static GvFlag[] putFlagsOnNetwork(FLyrVect layer,
491
                        Network net, double tolerance) throws BaseException {
492
                ReadableVectorial reader = layer.getSource();
493
                reader.start();
494
                IFeatureIterator it = reader.getFeatureIterator();
495
                int i=0;
496
                ArrayList<GvFlag> flags = new ArrayList();
497
                while (it.hasNext()) {
498
                        IFeature feat = it.next();
499
                        Geometry geo = feat.getGeometry().toJTSGeometry();
500
                        if (!((geo instanceof Point) || (geo instanceof MultiPoint)))
501
                                continue;
502
                        
503
                        
504

    
505
                        Coordinate[] coords = geo.getCoordinates();
506
//                        if (coords.length > 1) {
507
//                                logger.warn("The record " + i + " has " + coords.length + " coordinates. Pay attention!!");
508
//                        }
509
                        for (int j = 0; j < coords.length; j++) {
510
                                GvFlag flag = net.addFlag(coords[j].x, coords[j].y, tolerance);
511
                                if (flag == null)
512
                                {
513
                                        GraphException e = new GraphException("Punto " + i + " fuera de la red. Tolerancia=" + tolerance);
514
                                        e.setCode(GraphException.FLAG_OUT_NETWORK);
515
                                        throw e;
516
//                                        NotificationManager.addError("No se puedo situar el registro " + i + 
517
//                                                                " Por favor, compruebe que est? encima de la red o aumente la tolerancia.", e);
518
                                }
519
                                flags.add(flag);
520
                                flag.getProperties().put("rec", new Integer(i));
521
                        }        
522
                        i++;
523
                }
524
                it.closeIterator();
525
                reader.stop();
526
                return flags.toArray(new GvFlag[0]);
527
        }
528

    
529
}