Debian Codegraph @

src/footleg/cavesurvey/data/reader/DxfParser.java

raw symbols SCIP
1 /**
2 * Copyright (C) 2009-2017 Paul Fretwell - aka 'Footleg' ([email protected])
3 *
4 * This file is part of Cave Converter.
5 *
6 * Cave Converter is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * Cave Converter is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with Cave Converter. If not, see <http://www.gnu.org/licenses/>.
18 */
19 package footleg.cavesurvey.data.reader;
20
21 import java.util.ArrayList;
22 import java.util.Date;
23 import java.util.List;
24
25 import footleg.cavesurvey.converter.Logger;
26 import footleg.cavesurvey.converter.CaveConverter.BearingUnit;
27 import footleg.cavesurvey.converter.CaveConverter.GradientUnit;
28 import footleg.cavesurvey.converter.CaveConverter.LengthUnit;
29 import footleg.cavesurvey.data.model.CaveSurvey;
30 import footleg.cavesurvey.data.model.SurveyLeg;
31 import footleg.cavesurvey.data.model.SurveySeries;
32 import footleg.cavesurvey.data.model.SurveyStation;
33 import footleg.cavesurvey.data.model.SurveyStation.FixType;
34 import footleg.cavesurvey.tools.UtilityFunctions;
35
36 /**
37 * Parser for DXF format text data files.
38 *
39 * @author Footleg
40 * @version 2017.01.09 (ISO 8601 YYYY.MM.DD)
41 * @since 1.6 (The Java version used)
42 */
43 public class DxfParser {
44 private Date seriesDate;
45 private Logger logger;
46
47 /**
48 * Class constructor
49 * @param logger Logging class to output information, warning and error messages to
50 */
51 public DxfParser( Logger logger ) {
52 super();
53 this.logger = logger;
54 }
55
56 /**
57 * Parse Autocad DXF file into the cave data model.
58 *
59 * Converts polylines into series with fixed point at start.
60 *
61 * @param surveyFileData ListArray of data lines from a DXF file
62 * @param parseMode An enumeration to indicate whether to parse file for contour polylines, spot heights or survey legs
63 * @return Cave Survey object
64 *
65 * @to.do
66 * TODO Add option to round to nearest 10cm or 0.5 deg.
67 */
68 public CaveSurvey parseFile( List<String> surveyFileData, int parseMode ) {
69 int legCount = 0;
70 int iPolylineCount = 0;
71 int iVertexCount = 0;
72 int iPlainlineCount = 0;
73
74 //Create new list of survey series to hold data
75 CaveSurvey surveyData = new CaveSurvey(logger);
76 SurveySeries outerSeries = null;
77
78 //Create arrays to data while processing lines
79 List<List<double[]>> allChains = new ArrayList<List<double[]>>();
80 List<String[]> allChainLabels = new ArrayList<String[]>();
81 List<double[]> arSurveyChain = new ArrayList<double[]>();
82 List<double[]> arLines = new ArrayList<double[]>();
83 List<double[]> arLabelPoints = new ArrayList<double[]>();
84 List<String> arLabels = new ArrayList<String>();
85 boolean mappedLabelsFound = false;
86
87 //Define read state values
88 final int stateParsingHeader = 0;
89 final int stateFindPolyline = 1;
90 final int stateFindVertex = 2;
91
92 final int parseModeSurveyLegs = 0;
93 final int parseModeSurfaceContours = 1;
94 final int parseModeSpotHeights = 2;
95
96 //Initialise read state
97 int state = stateParsingHeader;
98
99 //Local vars
100 int iPointCount = 0;
101 String sLineName = "";
102 double dEastValue = 0;
103 double dNorthValue = 0;
104 double dElevValue = 0;
105 double dLastEastValue = 0;
106 double dLastNorthValue = 0;
107 double dLastElevValue = 0;
108
109 //Range bounds
110 //TODO Promote these to parameters which can be specified as options
111 int iNorthEdge = 999999999;
112 int iSouthEdge = -999999999;
113 int iEastEdge = 999999999;
114 int iWestEdge = -999999999;
115 int iMinElev = -999999999;
116
117 //Write output file header
118 logger.logMessage("Generating survey data from lines and polylines in DXF data file");
119 outerSeries = new SurveySeries( "SurveyFromDXF" );
120
121 //Loop through all data lines
122 for ( int i=0; i < surveyFileData.size(); i++ ) {
123 String dataLine = surveyFileData.get(i);
124
125 //Proceed based on state
126 switch( state ) {
127 case stateParsingHeader :
128 //First look for line:
129 // ENTITIES
130 //This signifies start of data after header stuff which we ignore.
131 if ( dataLine.trim().compareToIgnoreCase("ENTITIES") == 0 ) {
132 //Found end of header section, so change state to searching for new polyline
133 state = stateFindPolyline;
134 }
135 break;
136 case stateFindPolyline:
137 if ( dataLine.trim().compareToIgnoreCase("POLYLINE") == 0 ) {
138 //Found polyline, indicated with header line:
139 // POLYLINE
140 //and ending with:
141 // SEQEND
142
143 //Check next 15 lines looking for AcDbEntity start
144 int iSkipLoop = 1;
145 do {
146 dataLine = surveyFileData.get(++i);
147 }
148 while ( ( dataLine.trim().compareToIgnoreCase("AcDbEntity") != 0 )
149 || ( iSkipLoop > 15 ) );
150 //If found it then process
151 if ( dataLine.trim().compareToIgnoreCase("AcDbEntity") == 0 ) {
152 //(skip 1 line)
153 dataLine = surveyFileData.get(++i);
154 //Read entity type from next line:
155 dataLine = surveyFileData.get(++i);
156 //if Strings.Left(Trim(dataLine), 4) = "1100" {
157 //Found a contour line entity (they are all 1100x)
158 //Increment line counter
159 iPolylineCount += 1;
160 //Start new section heading, removing spaces from station names
161 sLineName = dataLine.replace(" ", "_");
162 if ( parseMode == parseModeSurfaceContours ) {
163 sLineName = sLineName + iPolylineCount;
164 }
165 //Set state to finding vertices
166 state = stateFindVertex;
167 //Reset point counter
168 iPointCount = 0;
169 //}
170 }
171 }
172 //loop through all lines, each indicated with header line:
173 // LINE
174 //and ending after a fixed number of lines
175 else if ( dataLine.trim().compareToIgnoreCase("LINE") == 0 ) {
176 //Found line
177 iPlainlineCount++;
178 //Check next 4 lines looking for AcDbEntity start
179 int iSkipLoop = 0;
180 do {
181 dataLine = surveyFileData.get(++i);
182 iSkipLoop++;
183 }
184 while ( (dataLine.trim().compareToIgnoreCase("AcDbEntity") != 0 && dataLine.trim().compareToIgnoreCase("CentreLine") != 0 )
185 && ( iSkipLoop < 4 ) );
186 //Allow anything if 4 lines read
187 boolean allowAnyLineName = false;
188 if ( iSkipLoop == 4 ) {
189 allowAnyLineName = true;
190 }
191 //If found it then process
192 if ( dataLine.trim().compareToIgnoreCase("AcDbEntity") == 0
193 || dataLine.trim().compareToIgnoreCase("CentreLine") == 0
194 || allowAnyLineName == true ) {
195 if ( dataLine.trim().compareToIgnoreCase("CentreLine") != 0 && allowAnyLineName == false ) {
196 //Check next 15 lines looking for AcDbLine start
197 iSkipLoop = 1;
198 do {
199 dataLine = surveyFileData.get(++i);
200 }
201 while ( ( dataLine.trim().compareToIgnoreCase("AcDbLine") != 0 )
202 || ( iSkipLoop > 15 ) );
203 }
204 //If found it then process
205 if ( dataLine.trim().compareToIgnoreCase("AcDbLine") == 0
206 || ( dataLine.trim().compareToIgnoreCase("CentreLine") == 0 )
207 || allowAnyLineName ) {
208 //Check for next line:
209 //10:
210 dataLine = surveyFileData.get(++i);
211 if ( dataLine.trim().compareToIgnoreCase("10") == 0 ) {
212 //Read Easting
213 dataLine = surveyFileData.get(++i);
214 dEastValue = roundedDataValue(dataLine);
215 //Check for next line:
216 //20:
217 dataLine = surveyFileData.get(++i);
218 if ( dataLine.trim().compareToIgnoreCase("20") == 0 ) {
219 //Read Northing
220 dataLine = surveyFileData.get(++i);
221 dNorthValue = roundedDataValue(dataLine);
222 //Check for next line:
223 //30:
224 dataLine = surveyFileData.get(++i);
225 if ( dataLine.trim().compareToIgnoreCase("30") == 0 ) {
226 //Read Elevation
227 dataLine = surveyFileData.get(++i);
228 dElevValue = roundedDataValue(dataLine);
229 //Check for next line:
230 //11:
231 dataLine = surveyFileData.get(++i);
232 if ( dataLine.trim().compareToIgnoreCase("11") == 0 ) {
233 //Read Easting
234 dataLine = surveyFileData.get(++i);
235 dLastEastValue = roundedDataValue(dataLine);
236 //Check for next line:
237 //21:
238 dataLine = surveyFileData.get(++i);
239 if ( dataLine.trim().compareToIgnoreCase("21") == 0 ) {
240 //Read Northing
241 dataLine = surveyFileData.get(++i);
242 dLastNorthValue = roundedDataValue(dataLine);
243 //Check for next line:
244 //31:
245 dataLine = surveyFileData.get(++i);
246 if ( dataLine.trim().compareToIgnoreCase("31") == 0 ) {
247 //Read Elevation
248 dataLine = surveyFileData.get(++i);
249 dLastElevValue = roundedDataValue(dataLine);
250 //Now generate data to output
251 if ( ( dEastValue >= iWestEdge )
252 && ( dEastValue <= iEastEdge )
253 && ( dNorthValue <= iNorthEdge )
254 && ( dNorthValue >= iSouthEdge )
255 && ( dElevValue >= iMinElev )
256 && ( dLastEastValue >= iWestEdge )
257 && ( dLastEastValue <= iEastEdge )
258 && ( dLastNorthValue <= iNorthEdge )
259 && ( dLastNorthValue >= iSouthEdge )
260 && ( dLastElevValue >= iMinElev )) {
261 //Increment point counter
262 iPointCount += 1;
263
264 if ( parseMode == parseModeSurveyLegs ) {
265 //Add points to line array
266 double[] point = new double[6];
267 point[0] = dEastValue;
268 point[1] = dNorthValue;
269 point[2] = dElevValue;
270 point[3] = dLastEastValue;
271 point[4] = dLastNorthValue;
272 point[5] = dLastElevValue;
273 arLines.add(point);
274 }
275 }
276 else {
277 //Record outside specified area
278 dEastValue = dNorthValue;
279 }
280 }
281 }
282 }
283 }
284 }
285 }
286 }
287 }
288 }
289 //loop through all text items, each indicated with header line:
290 // TEXT
291 //and ending after a fixed number of lines
292 else if ( dataLine.trim().compareToIgnoreCase("TEXT") == 0 ) {
293 //Found TEXT item
294 iPlainlineCount++;
295 //Skip next line then check for Label start
296 dataLine = surveyFileData.get(++i);
297 dataLine = surveyFileData.get(++i);
298 if (dataLine.trim().compareToIgnoreCase("Labels") == 0 ) {
299 //Found label, so read position and name from following lines
300
301 //Check for next line:
302 //10:
303 dataLine = surveyFileData.get(++i);
304 if ( dataLine.trim().compareToIgnoreCase("10") == 0 ) {
305 //Read Easting
306 dataLine = surveyFileData.get(++i);
307 dEastValue = roundedDataValue(dataLine);
308 //Check for next line:
309 //20:
310 dataLine = surveyFileData.get(++i);
311 if ( dataLine.trim().compareToIgnoreCase("20") == 0 ) {
312 //Read Northing
313 dataLine = surveyFileData.get(++i);
314 dNorthValue = roundedDataValue(dataLine);
315 //Check for next line:
316 //30:
317 dataLine = surveyFileData.get(++i);
318 if ( dataLine.trim().compareToIgnoreCase("30") == 0 ) {
319 //Read Elevation
320 dataLine = surveyFileData.get(++i);
321 dElevValue = roundedDataValue(dataLine);
322 //Skip 3 lines
323 for (int iskip = 0; iskip < 3; iskip++) {
324 dataLine = surveyFileData.get(++i);
325 }
326 //Next line should be station name
327 String possibleStnName = surveyFileData.get(++i);
328 //skip a line
329 dataLine = surveyFileData.get(++i);
330 //Check for next line:
331 //POINT:
332 dataLine = surveyFileData.get(++i);
333 if ( dataLine.trim().compareToIgnoreCase("POINT") == 0 ) {
334 //skip a line
335 dataLine = surveyFileData.get(++i);
336 //Check for next line:
337 //Stations:
338 dataLine = surveyFileData.get(++i);
339 if ( dataLine.trim().compareToIgnoreCase("Stations") == 0 ) {
340 //Check for next line:
341 //10:
342 dataLine = surveyFileData.get(++i);
343 if ( dataLine.trim().compareToIgnoreCase("10") == 0 ) {
344 //Read Easting
345 dataLine = surveyFileData.get(++i);
346 dLastEastValue = roundedDataValue(dataLine);
347 //Check for next line:
348 //20:
349 dataLine = surveyFileData.get(++i);
350 if ( dataLine.trim().compareToIgnoreCase("20") == 0 ) {
351 //Read Northing
352 dataLine = surveyFileData.get(++i);
353 dLastNorthValue = roundedDataValue(dataLine);
354 //Check for next line:
355 //30:
356 dataLine = surveyFileData.get(++i);
357 if ( dataLine.trim().compareToIgnoreCase("30") == 0 ) {
358 //Read Elevation
359 dataLine = surveyFileData.get(++i);
360 dLastElevValue = roundedDataValue(dataLine);
361 //Now generate data to output
362 if ( ( dEastValue >= iWestEdge )
363 && ( dEastValue <= iEastEdge )
364 && ( dNorthValue <= iNorthEdge )
365 && ( dNorthValue >= iSouthEdge )
366 && ( dElevValue >= iMinElev )
367 && ( dLastEastValue >= iWestEdge )
368 && ( dLastEastValue <= iEastEdge )
369 && ( dLastNorthValue <= iNorthEdge )
370 && ( dLastNorthValue >= iSouthEdge )
371 && ( dLastElevValue >= iMinElev )) {
372 //Check station point and label point matched
373 if ( ( dEastValue == dLastEastValue )
374 && ( dNorthValue == dLastNorthValue )
375 && ( dElevValue == dLastElevValue )) {
376
377 //Station label identified
378 if ( parseMode == parseModeSurveyLegs ) {
379 //Add label and point to lists
380 double[] point = new double[3];
381 point[0] = dEastValue;
382 point[1] = dNorthValue;
383 point[2] = dElevValue;
384 arLabels.add( possibleStnName );
385 arLabelPoints.add( point );
386 }
387 }
388 }
389 else {
390 //Record outside specified area
391 dEastValue = dNorthValue;
392 }
393 }
394 }
395 }
396 }
397 }
398 }
399 }
400 }
401 }
402 }
403 break;
404 case stateFindVertex:
405 //Within each polyline, look for vertices indicated by lines:
406 // VERTEX
407 if ( dataLine.trim().compareToIgnoreCase("VERTEX") == 0 ) {
408 //Reset flag
409 boolean bValidRecord = false;
410 //Increment count
411 iVertexCount += 1;
412 //Check next 15 lines looking for AcDbEntity start
413 int iSkipLoop = 1;
414 do {
415 dataLine = surveyFileData.get(++i);
416 }
417 while ( ( dataLine.trim().compareToIgnoreCase("AcDbEntity") != 0 )
418 || ( iSkipLoop > 15 ) );
419 if ( dataLine.trim().compareToIgnoreCase("AcDbEntity") == 0 ) {
420 //Check next 15 lines looking for AcDbVertex start
421 iSkipLoop = 1;
422 do {
423 dataLine = surveyFileData.get(++i);
424 }
425 while ( ( dataLine.trim().compareToIgnoreCase("AcDbVertex") != 0 )
426 || ( iSkipLoop > 15 ) );
427 if ( dataLine.trim().compareToIgnoreCase("AcDbVertex") == 0 ) {
428 //Check next 15 lines looking for AcDb3dPolylineVertex start
429 iSkipLoop = 1;
430 do {
431 dataLine = surveyFileData.get(++i);
432 }
433 while ( ( dataLine.trim().compareToIgnoreCase("AcDb3dPolylineVertex") != 0 )
434 || ( iSkipLoop > 15 ) );
435 if ( dataLine.trim().compareToIgnoreCase("AcDb3dPolylineVertex") == 0 ) {
436 //Check for next line:
437 //10:
438 dataLine = surveyFileData.get(++i);
439 if ( dataLine.trim().compareToIgnoreCase("10") == 0 ) {
440 //Read Easting
441 dataLine = surveyFileData.get(++i);
442 dEastValue = roundedDataValue(dataLine);
443 //Check for next line:
444 //20:
445 dataLine = surveyFileData.get(++i);
446 if ( dataLine.trim().compareToIgnoreCase("20") == 0 ) {
447 //Read Northing
448 dataLine = surveyFileData.get(++i);
449 dNorthValue = roundedDataValue(dataLine);
450 //Check for next line:
451 //30:
452 dataLine = surveyFileData.get(++i);
453 if ( dataLine.trim().compareToIgnoreCase("30") == 0 ) {
454 //Read Elevation
455 dataLine = surveyFileData.get(++i);
456 dElevValue = roundedDataValue(dataLine);
457 //Now generate data to output
458 if ( ( dEastValue >= iWestEdge )
459 && ( dEastValue <= iEastEdge )
460 && ( dNorthValue <= iNorthEdge )
461 && ( dNorthValue >= iSouthEdge )
462 && ( dElevValue >= iMinElev ) ) {
463 //Increment point counter
464 iPointCount += 1;
465
466 if ( parseMode == parseModeSurveyLegs ) {
467 //Add point to chain
468 double[] point = new double[3];
469 point[0] = dEastValue;
470 point[1] = dNorthValue;
471 point[2] = dElevValue;
472 arSurveyChain.add(point);
473 }
474 else {
475 //Generate station name
476 String sStnName = "S" + iPolylineCount + "P" + iPointCount;
477 //Reset station position string
478 String sPointPosition = "";
479 if ( iPointCount == 1 ) {
480 //First point, so fix it
481 sPointPosition = "*fix " + sStnName + " " +
482 dEastValue + " " +
483 dNorthValue + " " +
484 dElevValue;
485 if ( parseMode == parseModeSurfaceContours ) {
486 //Write line header
487 logger.logMessage("*begin " + sLineName);
488 }
489 else {
490 //} point, so write differences for leg
491 sPointPosition = " " + (dEastValue - dLastEastValue) + " " +
492 (dNorthValue - dLastNorthValue) + " " +
493 (dElevValue - dLastElevValue);
494 }
495 }
496 if ( parseMode == parseModeSpotHeights ) {
497 logger.logMessage( String.valueOf(Math.round(dEastValue) - iEastEdge) );
498 logger.logMessage( String.valueOf( (iNorthEdge - iSouthEdge) - ( Math.round(dNorthValue) - iSouthEdge) ) );
499 logger.logMessage( String.valueOf(dElevValue) );
500 }
501 else {
502 //Write position and station number
503 logger.logMessage(sPointPosition);
504 logger.logMessage(sStnName);
505 }
506 }
507 //Update last positions
508 dLastEastValue = dEastValue;
509 dLastNorthValue = dNorthValue;
510 dLastElevValue = dElevValue;
511 }
512 else {
513 //Record outside specified area
514 dEastValue = dNorthValue;
515 }
516 bValidRecord = true;
517 }
518 }
519 }
520 }
521 }
522 }
523 //Check for invalid records
524 if ( bValidRecord == false ) {
525 //Invalid record
526 logger.logMessage("Bad Line");
527 //Set state back to searching for next vertex
528 state = stateFindPolyline;
529 }
530 }
531 //Find either next VERTEX or SEQEND
532 else if ( dataLine.trim().compareToIgnoreCase("SEQEND") == 0 ) {
533 //End of polyline
534 //Write final station name if any points were written
535 if ( parseMode == parseModeSurveyLegs ) {
536 //Check that line name is unique
537 String sUniqueName = sLineName;
538 int k = 1;
539 boolean bUnique = false;
540 while ( bUnique == false ) {
541 //Search existing chains for matching name
542 bUnique = true;
543 for ( int j = 0; j < outerSeries.innerSeriesCount(); j++ ) {
544 //Check for matching series
545 if ( outerSeries.getInnerSeries(j).getSeriesName().compareTo( sUniqueName ) == 0 ) {
546 //Not unique, so add number to end
547 sUniqueName = sLineName + k;
548 k++;
549 bUnique = false;
550 //Exit loop
551 j = outerSeries.innerSeriesCount();
552 }
553 }
554 }
555
556 //If no label points, then pass the unique name from the line in via the labels array
557 if ( arLabelPoints.size() == 0 ) {
558 arLabels.add( 0, sUniqueName );
559 }
560
561 //Map points in chain to labels
562 String[] stnLabels = mapLabelsToChainPoints(arSurveyChain, arLabelPoints, arLabels);
563
564 //Add new series to list for this polyline
565 outerSeries.addSeries( makeSeriesFromPolyline( arSurveyChain, sUniqueName, stnLabels ) );
566 legCount += (arSurveyChain.size() - 1);
567
568 //Store chain and labels for this chain for linking to other chains later
569 allChains.add(arSurveyChain);
570 allChainLabels.add(stnLabels);
571 //Reset flag if station labels are null
572 if ( stnLabels[0] != null ) {
573 mappedLabelsFound = true;
574 }
575
576 //Reset series data array
577 arSurveyChain = new ArrayList<double[]>();
578
579 }
580 else if ( parseMode == parseModeSurfaceContours ) {
581 //End section if any points were in target area
582 if ( iPointCount > 0 ) {
583 logger.logMessage("*end " + sLineName);
584 }
585 }
586 //Set state back to searching for next vertex
587 state = stateFindPolyline;
588 }
589 break;
590 default:
591 }
592 }
593
594 //Attempt to join up lines into connected polylines
595 int newlines = 0;
596 while ( arLines.size() > 0 ) {
597 //Get first line out
598 double[] line = arLines.remove(0);
599 //Start new polyline
600 arSurveyChain = new ArrayList<double[]>();
601 //Add points to chain
602 double[] firstPoint = new double[3];
603 firstPoint[0] = line[0];
604 firstPoint[1] = line[1];
605 firstPoint[2] = line[2];
606 arSurveyChain.add(firstPoint);
607 double[] lastPoint = new double[3];
608 lastPoint[0] = line[3];
609 lastPoint[1] = line[4];
610 lastPoint[2] = line[5];
611 arSurveyChain.add(lastPoint);
612
613 //Search for adjoining lines
614 boolean added = true;
615 while ( added == true ) {
616 added = false;
617 for ( int linesIdx = 0; linesIdx < arLines.size(); linesIdx++ ) {
618 boolean match = false;
619 line = arLines.get(linesIdx);
620 if ( firstPoint[0] == line[0]
621 && firstPoint[1] == line[1]
622 && firstPoint[2] == line[2] ) {
623 //Add new first point to start of polyline
624 firstPoint = new double[3];
625 firstPoint[0] = line[3];
626 firstPoint[1] = line[4];
627 firstPoint[2] = line[5];
628 arSurveyChain.add(0, firstPoint);
629 match = true;
630 }
631 else if ( firstPoint[0] == line[3]
632 && firstPoint[1] == line[4]
633 && firstPoint[2] == line[5] ) {
634 //Add new first point to start of polyline
635 firstPoint = new double[3];
636 firstPoint[0] = line[0];
637 firstPoint[1] = line[1];
638 firstPoint[2] = line[2];
639 arSurveyChain.add(0, firstPoint);
640 match = true;
641 }
642 else if ( lastPoint[0] == line[0]
643 && lastPoint[1] == line[1]
644 && lastPoint[2] == line[2] ) {
645 //Add new last point to end of polyline
646 lastPoint = new double[3];
647 lastPoint[0] = line[3];
648 lastPoint[1] = line[4];
649 lastPoint[2] = line[5];
650 arSurveyChain.add(lastPoint);
651 match = true;
652 }
653 else if ( lastPoint[0] == line[3]
654 && lastPoint[1] == line[4]
655 && lastPoint[2] == line[5] ) {
656 //Add new last point to end of polyline
657 lastPoint = new double[3];
658 lastPoint[0] = line[0];
659 lastPoint[1] = line[1];
660 lastPoint[2] = line[2];
661 arSurveyChain.add(lastPoint);
662 match = true;
663 }
664 if ( match == true ) {
665 //Remove line and decrement index so next item is picked up
666 arLines.remove(linesIdx);
667 linesIdx--;
668 added = true;
669 }
670 }
671 }
672
673 //Map points in chain to labels
674 String[] stnLabels = mapLabelsToChainPoints(arSurveyChain, arLabelPoints, arLabels);
675 if ( arLabels.size() > 0 ) {
676 mappedLabelsFound = true;
677 }
678
679 //Add chain to array and create series
680 newlines++;
681 String sSeriesName = "SeriesFromLines" + newlines;
682 SurveySeries newSeries = makeSeriesFromPolyline( arSurveyChain, sSeriesName, stnLabels );
683 //Add series if it contains any legs (polylines where all points share the same location do not generate any legs)
684 if ( newSeries.legCount() > 0 ) {
685 allChains.add(arSurveyChain);
686 allChainLabels.add(stnLabels);
687 outerSeries.addSeries( newSeries );
688 legCount += (arSurveyChain.size() - 1);
689 }
690 }
691
692 if ( mappedLabelsFound ) {
693 //DXF has mapped labels for all chains. Rebuild series based on full station names.
694 SurveySeries rebuiltOuterSeries = new SurveySeries("SurveyFromDXFExportedFrom3D");
695 for ( int seriesIdx = 0; seriesIdx < outerSeries.innerSeriesCount(); seriesIdx++ ) {
696 //Get chain corresponding to this series
697 List<double[]> srcChain = allChains.get(seriesIdx);
698 //Search through all legs in the series and put each into a new series matching the station name prefix
699 SurveySeries inputSeries = outerSeries.getInnerSeries( seriesIdx );
700 for ( int legIdx = 0; legIdx < inputSeries.legCount(); legIdx++ ) {
701 SurveyLeg inputLeg = inputSeries.getLegRaw( legIdx );
702
703 //Find series for from stn in this leg
704 String fromStnName = inputLeg.getFromStn().getName();
705
706 int matchingFromSeries = findMatchingSeriesForStnName( rebuiltOuterSeries, fromStnName );
707 if ( matchingFromSeries > -1 ) {
708 String toStnName = inputLeg.getToStn().getName();
709 int matchingToSeries = findMatchingSeriesForStnName( rebuiltOuterSeries, toStnName );
710 int legNewSeries = matchingFromSeries;
711 if ( matchingToSeries != matchingFromSeries ) {
712 //fromStn series does not match toStn series, so we need to determine which series this leg belongs to
713 boolean stnNameSwapped = false;
714 //Check if toStn has more than one matching point in the all points array
715 List<Integer> matchingToPoints = getListOfMatchingPoints( srcChain.get( legIdx + 1 ), arLabelPoints );
716 if ( matchingToPoints.size() > 1 ) {
717 //Look for matching point label which does match the from station series
718 String fromStnPrefix = getNamePrefix( fromStnName );
719 if ( fromStnPrefix.length() > 0 ) {
720 String toStnPrefix = getNamePrefix( toStnName );
721 if ( toStnPrefix.length() > 0 ) {
722 for ( int matchingPointsIdx = 0; matchingPointsIdx < matchingToPoints.size(); matchingPointsIdx++ ) {
723 String testLabel = arLabels.get( matchingToPoints.get(matchingPointsIdx) );
724 String testLabelPrefix = getNamePrefix( testLabel );
725 if ( testLabelPrefix.equals(fromStnPrefix) ) {
726 //Replace the toStnName with the matching point which does match the from station prefix
727 inputLeg.getToStn().setName( testLabel );
728 //Add an equate for the alternate names being swapped for this stn
729 SurveyStation linkStn1 = new SurveyStation(0);
730 linkStn1.setName( getShortenedName( testLabel ) );
731 SurveyStation linkStn2 = new SurveyStation(0);
732 linkStn2.setName( getShortenedName( toStnName ) );
733 //TODO Only add link if not already present
734 rebuiltOuterSeries.addLink(rebuiltOuterSeries.getInnerSeries(matchingFromSeries).getSeriesName(),linkStn1,
735 rebuiltOuterSeries.getInnerSeries(matchingToSeries).getSeriesName(), linkStn2);
736 stnNameSwapped = true;
737 break;
738 }
739 }
740 }
741 }
742 }
743 if ( stnNameSwapped == false ) {
744 //No matching point for toStn was in the same series as the fromStn, so we need to find
745 //a matching label for the fromStn which is in the toStn series
746
747 //Check if fromStn has more than one matching point in the all points array
748 List<Integer> matchingFromPoints = getListOfMatchingPoints( srcChain.get( legIdx ), arLabelPoints );
749 if ( matchingFromPoints.size() > 1 ) {
750 //Look for matching point label which does match the from station series
751 String fromStnPrefix = getNamePrefix( fromStnName );
752 if ( fromStnPrefix.length() > 0 ) {
753 String toStnPrefix = getNamePrefix( toStnName );
754 if ( toStnPrefix.length() > 0 ) {
755 for ( int matchingPointsIdx = 0; matchingPointsIdx < matchingFromPoints.size(); matchingPointsIdx++ ) {
756 String testLabel = arLabels.get( matchingFromPoints.get(matchingPointsIdx) );
757 String testLabelPrefix = getNamePrefix( testLabel );
758 if ( testLabelPrefix.equals(toStnPrefix) ) {
759 //Replace the fromStnName with the matching point which does match the to station prefix
760 inputLeg.getFromStn().setName( testLabel );
761 //Add an equate for the alternate names being swapped for this stn
762 SurveyStation linkStn1 = new SurveyStation(0);
763 linkStn1.setName( getShortenedName( fromStnName ) );
764 SurveyStation linkStn2 = new SurveyStation(0);
765 linkStn2.setName( getShortenedName( testLabel ) );
766 //TODO Only add link if not already present
767 rebuiltOuterSeries.addLink(rebuiltOuterSeries.getInnerSeries(matchingFromSeries).getSeriesName(),linkStn1,
768 rebuiltOuterSeries.getInnerSeries(matchingToSeries).getSeriesName(), linkStn2);
769 legNewSeries = matchingToSeries;
770 break;
771 }
772 }
773 }
774 }
775 }
776
777 }
778 }
779
780 //Remove the prefixes from both stations in each leg
781 String shortenedFromName = getShortenedName( inputLeg.getFromStn().getName() );
782 String shortenedToName = getShortenedName( inputLeg.getToStn().getName() ) ;
783 inputLeg.getFromStn().setName( shortenedFromName );
784 inputLeg.getToStn().setName( shortenedToName );
785
786 //Put leg into matching series in rebuilt survey after all changes to the station names
787 rebuiltOuterSeries.getInnerSeries( legNewSeries ).addLeg( inputLeg );
788 }
789 }
790 }
791
792
793
794 //Replace original with rebuilt series set
795 outerSeries = rebuiltOuterSeries;
796 }
797 else {
798 //Search for connected stations for any station in each polyline
799 for ( int seriesIdx = 0; seriesIdx < outerSeries.innerSeriesCount(); seriesIdx++ ) {
800 //Get chain corresponding to this series
801 List<double[]> srcChain = allChains.get(seriesIdx);
802 String[] srcChainLabels = allChainLabels.get(seriesIdx);
803 for ( int point1Idx = 0; point1Idx < srcChain.size(); point1Idx++ ) {
804 //Get fixed position for this station in chain
805 double fixX = srcChain.get(point1Idx)[0];
806 double fixY = srcChain.get(point1Idx)[1];
807 double fixZ = srcChain.get(point1Idx)[2];
808 //Check all chains except self for a matching point
809 for ( int chainIdx = 0; chainIdx < allChains.size(); chainIdx++ ) {
810 List<double[]> chain = allChains.get(chainIdx);
811 String[] chainLabels = allChainLabels.get(chainIdx);
812 for ( int pointIdx = 0; pointIdx < chain.size(); pointIdx++ ) {
813 if ( ( fixX == chain.get(pointIdx)[0] )
814 && ( fixY == chain.get(pointIdx)[1] )
815 && ( fixZ == chain.get(pointIdx)[2] ) ) {
816 //Found matching point
817 boolean addEquate = true;
818 if (chainIdx == seriesIdx ) {
819 //Matching point is in same series, so only add equate
820 //when matching station occurs after test station to avoid adding
821 //equate twice or equating stations onto themselves
822 if ( pointIdx <= point1Idx) {
823 addEquate = false;
824 }
825 }
826 if ( addEquate == true ) {
827 //Replace fixed point in leg with equate
828 SurveyStation linkStn1 = new SurveyStation(point1Idx);
829 if ( srcChainLabels[point1Idx] != null ) {
830 linkStn1.setName( srcChainLabels[point1Idx] );
831 }
832 SurveyStation linkStn2 = new SurveyStation(pointIdx);
833 if ( chainLabels[pointIdx] != null ) {
834 linkStn2.setName( chainLabels[pointIdx] );
835 }
836 outerSeries.addLink(outerSeries.getInnerSeries(seriesIdx).getSeriesName(), linkStn1,
837 outerSeries.getInnerSeries(chainIdx).getSeriesName(), linkStn2);
838 }
839 //Clear fixed points apart from first one in first series
840 if ( seriesIdx > 0 ) {
841 SurveyStation stn = outerSeries.getInnerSeries(seriesIdx).getLegRaw(0).getFromStn();
842 // double easting = stn.getEasting();
843 // double northing = stn.getNorthing();
844 // double altitude = stn.getAltitude();
845 // stn.setFixed(FixType.NONE, easting, northing, altitude);
846 stn.clearFixedStn();
847 }
848 }
849 }
850 }
851 }
852 }
853 }
854
855 //Put generated data series into survey
856 surveyData.add( outerSeries );
857
858 //Debug dump
859 UtilityFunctions.logSurveyDebugData(surveyData, logger);
860
861 //Completed file parsing
862 logger.logMessage("Processed " + legCount + " survey legs in " +
863 outerSeries.innerSeriesCount() + " series.");
864 logger.logMessage("Found:");
865 logger.logMessage("Polylines: " + iPolylineCount + " containing " + iVertexCount + " line segments.");
866 logger.logMessage("Lines: " + iPlainlineCount);
867 logger.logMessage("Total line segments: " + (iPlainlineCount + iVertexCount));
868
869 return surveyData;
870 }
871
872 /**
873 * Search for an inner series matching the name prefix on this station, and return it. If
874 * not found then create it and return it.
875 *
876 * @param series Series containing an inner series to match by name to the stn name
877 * @param stnName Stn name to match
878 * @return Matching inner series index
879 */
880 private int findMatchingSeriesForStnName( SurveySeries series, String stnName ) {
881 int matchingIdx = -1;
882
883 //Determine prefix from station name
884 String stnPrefix = getNamePrefix( stnName );
885 if ( stnPrefix.length() > 0 ) {
886 for (int i = 0; i < series.innerSeriesCount(); i++ ) {
887 String seriesName = series.getInnerSeries( i ).getSeriesName();
888 if ( stnPrefix.equalsIgnoreCase( seriesName ) ) {
889 matchingIdx = i;
890 break;
891 }
892 }
893
894 //If not match found then create a new series for this name
895 if ( matchingIdx == -1 ) {
896 SurveySeries newSeries = new SurveySeries( stnPrefix );
897 series.addSeries( newSeries );
898 matchingIdx = series.innerSeriesCount() - 1;
899 }
900 }
901
902 return matchingIdx;
903 }
904
905 /**
906 * Takes a survey chain array, label points array and station labels array, and generates an array
907 * of labels for all the points in the chain. The index of any point in the chain will be the same
908 * a the index of the corresponding label in the output array.
909 * @param arSurveyChain Chain of points representing a survey chain (linear chain of legs)
910 * @param arLabelPoints Array of points which correspond the labels in the labels array
911 * @param stnLabels Array of labels corresponding to the points in the label points array
912 * @return Array of labels corresponding to the points in the survey chain
913 */
914 private String[] mapLabelsToChainPoints( List<double[]> arSurveyChain, List<double[]> arLabelPoints,
915 List<String> stnLabels ) {
916
917 //Create an array of labels and set them to the matching points
918 String[] labels = new String[arSurveyChain.size()];
919 for ( int i = 0; i < arSurveyChain.size(); i++ ) {
920 double[] chainPoint = arSurveyChain.get(i);
921 for ( int j = 0; j < arLabelPoints.size(); j++ ) {
922 //Check if point matches chain point
923 if ( ( chainPoint[0] == arLabelPoints.get(j)[0] )
924 && ( chainPoint[1] == arLabelPoints.get(j)[1] )
925 && ( chainPoint[2] == arLabelPoints.get(j)[2] ) ) {
926 labels[i] = stnLabels.get(j);
927 break;
928 }
929 }
930 }
931
932 return labels;
933
934 }
935
936 /**
937 * Converts a series of points in a polyline with absolute coordinates into a series
938 * of connected survey legs,calculating tape, compass and clino data.
939 * @param List<double[]> List of all points in polyline as x,y,z coordinates
940 * @return SurveySeries of all the legs represented by the polyline. Fixed by position of first stn.
941 */
942 private SurveySeries makeSeriesFromPolyline( List<double[]> arSurveyChain, String seriesName, String[] labels ) {
943 //Create new series from this chain
944 SurveySeries series = new SurveySeries( seriesName );
945
946 //Set date
947 series.setSurveyDate( seriesDate );
948
949 //Loop through all points in chain
950 for ( int i = 1; i < arSurveyChain.size(); i++ ) {
951 SurveyLeg leg = new SurveyLeg();
952 SurveyStation fromStn = new SurveyStation( i - 1 );
953 SurveyStation toStn = new SurveyStation( i );
954 double[] startPoint = arSurveyChain.get( i - 1 );
955 double[] endPoint = arSurveyChain.get(i);
956
957 if ( i == 1 ) {
958 //First leg, so fix first station
959 fromStn.setFixed(FixType.OTHER, startPoint[0], startPoint[1], startPoint[2]);
960 }
961
962 //Calculate leg data
963 double x = endPoint[0] - startPoint[0];
964 double y = endPoint[1] - startPoint[1];
965 double z = endPoint[2] - startPoint[2];
966
967 //Only add point if in a different position to previous point in polyline (or series is only two points forming an equate)
968 if ( x != 0 || y != 0 || z != 0 || arSurveyChain.size() == 2 ) {
969 double hori = Math.pow( Math.pow( x, 2 ) + Math.pow( y, 2 ), 0.5 );
970 double tape = Math.pow( Math.pow( hori, 2 ) + Math.pow( z, 2 ), 0.5 );
971 double compass = bearing(x, y);
972 double clino = bearing(z, hori);
973 if ( clino > 90 ) {
974 clino = clino - 360;
975 }
976 //Set stn names from labels array if we have them
977 if (labels[i-1] != null) {
978 fromStn.setName( labels[i-1] );
979 }
980 if (labels[i] != null) {
981 toStn.setName( labels[i] );
982 }
983
984 leg.setFromStn( fromStn );
985 leg.setToStn( toStn );
986 leg.setLength( tape, LengthUnit.Metres );
987 leg.setCompass( compass, BearingUnit.Degrees );
988 leg.setClino( clino, GradientUnit.Degrees );
989
990 series.addLeg(leg);
991 }
992 }
993
994 // CleanSeries(series);
995
996 return series;
997 }
998
999 /**
1000 * bearing
1001 *
1002 * Returns bearing for angle described by x and y lengths
1003 */
1004 private double bearing(double x, double y) {
1005 double res = 0;
1006
1007 if ( x == 0 ) {
1008 if ( y < 0 ) {
1009 res = 180;
1010 }
1011 else {
1012 res = 0;
1013 }
1014 }
1015 else if ( x < 0 ) {
1016 if ( y == 0 ) {
1017 res = 270;
1018 }
1019 else if ( y < 0 ) {
1020 //180-270
1021 res = 180 + (Math.atan(x / y) * 180 / Math.PI);
1022 }
1023 else {
1024 //270-360
1025 res = 360 + (Math.atan(x / y) * 180 / Math.PI);
1026 }
1027 }
1028 else {
1029 if ( y == 0 ) {
1030 res = 90;
1031 }
1032 else if ( y < 0 ) {
1033 //90-180
1034 res = 180 + (Math.atan(x / y) * 180 / Math.PI);
1035 }
1036 else {
1037 //0-90
1038 res = (Math.atan(x / y) * 180 / Math.PI);
1039 }
1040 }
1041
1042 return res;
1043 }
1044
1045 private double roundedDataValue( String dataLine ) {
1046 double roundedVal = ( (double)Math.round( Double.valueOf(dataLine) * 10000 ) ) / 10000;
1047
1048 return roundedVal;
1049 }
1050
1051 /**
1052 * Clean up names in the survey series
1053 * @param series
1054 */
1055 private void CleanSeries( SurveySeries series ) {
1056 //Count occurrences of each unique prefix on station names
1057 List<String> stnNamePrefixes = new ArrayList<String>();
1058 List<Integer> stnNamePrefixCounts = new ArrayList<Integer>();
1059
1060 for ( int i = 0; i < series.legCount(); i++ ) {
1061 SurveyLeg leg = series.getLegRaw( i );
1062
1063 String name = leg.getFromStn().getName();
1064 if ( name.contains(".") ) {
1065 String prefix = name.substring( 0, name.lastIndexOf('.') );
1066 boolean found = false;
1067 for ( int j = 0; j < stnNamePrefixes.size(); j++ ) {
1068 if ( prefix.equals( stnNamePrefixes.get(j) ) ) {
1069 found = true;
1070 int count = stnNamePrefixCounts.get(j);
1071 count++;
1072 stnNamePrefixCounts.set(j, count);
1073 break;
1074 }
1075 }
1076 if ( found == false ) {
1077 stnNamePrefixes.add( prefix );
1078 stnNamePrefixCounts.add(1);
1079 }
1080 }
1081
1082 name = leg.getToStn().getName();
1083 if ( name.contains(".") ) {
1084 String prefix = name.substring( 0, name.lastIndexOf('.') );
1085 boolean found = false;
1086 for ( int j = 0; j < stnNamePrefixes.size(); j++ ) {
1087 if ( prefix.equals( stnNamePrefixes.get(j) ) ) {
1088 found = true;
1089 int count = stnNamePrefixCounts.get(j);
1090 count++;
1091 stnNamePrefixCounts.set(j, count);
1092 break;
1093 }
1094 }
1095 if ( found == false ) {
1096 stnNamePrefixes.add( prefix );
1097 stnNamePrefixCounts.add(1);
1098 }
1099 }
1100 }
1101
1102 if ( stnNamePrefixes.size() > 0 ) {
1103 //Find most common prefix then remove it from all station names and use as series name
1104 int mostCommonPrefixIdx = 0;
1105 int highestOccurence = 0;
1106 for ( int j = 0; j < stnNamePrefixCounts.size(); j++ ) {
1107 if ( stnNamePrefixCounts.get(j) > highestOccurence ) {
1108 mostCommonPrefixIdx = j;
1109 highestOccurence = stnNamePrefixCounts.get(j);
1110 }
1111 }
1112
1113 //Rename series using most common prefix
1114 series.setSeriesName( stnNamePrefixes.get( mostCommonPrefixIdx ) );
1115 }
1116
1117 }
1118
1119 /**
1120 * Determines the prefix for a station name (all the string up to the last dot separator)
1121 * @param name Station name to examine
1122 * @return Prefix from the name, or an empty string if no dit separator in name.
1123 */
1124 private String getNamePrefix( String name ) {
1125 int lastDotPos = name.lastIndexOf('.');
1126 String prefix = "";
1127 if ( lastDotPos > -1 ) {
1128 prefix = name.substring( 0, lastDotPos );
1129 }
1130 return prefix;
1131 }
1132
1133 /**
1134 * Determines the station name after the prefix (all the string after the last dot separator)
1135 * @param name Station name to examine
1136 * @return Shortened station name
1137 */
1138 private String getShortenedName( String name ) {
1139 int lastDotPos = name.lastIndexOf('.');
1140 String shortName = name;
1141 if ( lastDotPos > -1 ) {
1142 shortName = name.substring( lastDotPos + 1 );
1143 }
1144 return shortName;
1145 }
1146
1147 /**
1148 * Returns a list of the indices in the label points array of all points matching the position of a given point
1149 * @param matchingPoint The point to match
1150 * @param labelPoints Array of points to search for matching points in
1151 * @return ArrayList of the indices of all points at the same coordinates as the specified point
1152 */
1153 private List<Integer> getListOfMatchingPoints(double[] matchingPoint, List<double[]> labelPoints) {
1154 List<Integer> matchingPoints = new ArrayList<Integer>();
1155 for ( int allPointsIdx = 0; allPointsIdx < labelPoints.size(); allPointsIdx++ ) {
1156 double[] testPoint = labelPoints.get( allPointsIdx );
1157 if ( ( matchingPoint[0] == testPoint[0])
1158 && ( matchingPoint[1] == testPoint[1])
1159 && ( matchingPoint[2] == testPoint[2]) ) {
1160 //Add index of matching point to matches array
1161 matchingPoints.add( allPointsIdx );
1162 }
1163 }
1164 return matchingPoints;
1165 }
1166 }