]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/save/PovExporter.java
c00274787a0f458ebddadbe092070045e1a6ce7f
[GpsPrune.git] / tim / prune / save / PovExporter.java
1 package tim.prune.save;
2
3 import java.awt.BorderLayout;
4 import java.awt.Component;
5 import java.awt.FlowLayout;
6 import java.awt.GridLayout;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9 import java.io.File;
10 import java.io.FileWriter;
11 import java.io.IOException;
12 import java.util.ArrayList;
13 import java.util.Iterator;
14
15 import javax.imageio.ImageIO;
16 import javax.swing.BorderFactory;
17 import javax.swing.Box;
18 import javax.swing.BoxLayout;
19 import javax.swing.ButtonGroup;
20 import javax.swing.JButton;
21 import javax.swing.JDialog;
22 import javax.swing.JFileChooser;
23 import javax.swing.JLabel;
24 import javax.swing.JOptionPane;
25 import javax.swing.JPanel;
26 import javax.swing.JRadioButton;
27 import javax.swing.JTextField;
28 import javax.swing.SwingConstants;
29
30 import tim.prune.App;
31 import tim.prune.FunctionLibrary;
32 import tim.prune.I18nManager;
33 import tim.prune.UpdateMessageBroker;
34 import tim.prune.config.Config;
35 import tim.prune.data.NumberUtils;
36 import tim.prune.data.Track;
37 import tim.prune.function.Export3dFunction;
38 import tim.prune.function.srtm.LookupSrtmFunction;
39 import tim.prune.gui.BaseImageDefinitionPanel;
40 import tim.prune.gui.DialogCloser;
41 import tim.prune.gui.TerrainDefinitionPanel;
42 import tim.prune.gui.map.MapSource;
43 import tim.prune.gui.map.MapSourceLibrary;
44 import tim.prune.load.GenericFileFilter;
45 import tim.prune.threedee.ImageDefinition;
46 import tim.prune.threedee.TerrainCache;
47 import tim.prune.threedee.TerrainDefinition;
48 import tim.prune.threedee.TerrainHelper;
49 import tim.prune.threedee.ThreeDModel;
50
51 /**
52  * Class to export a 3d scene of the track to a specified Pov file
53  */
54 public class PovExporter extends Export3dFunction
55 {
56         private Track _track = null;
57         private JDialog _dialog = null;
58         private JFileChooser _fileChooser = null;
59         private String _cameraX = null, _cameraY = null, _cameraZ = null;
60         private JTextField _cameraXField = null, _cameraYField = null, _cameraZField = null;
61         private JTextField _fontName = null, _altitudeFactorField = null;
62         private JRadioButton _ballsAndSticksButton = null;
63         /** Panel for defining the base image */
64         private BaseImageDefinitionPanel _baseImagePanel = null;
65         /** Component for defining the terrain */
66         private TerrainDefinitionPanel _terrainPanel = null;
67
68         // defaults
69         private static final double DEFAULT_CAMERA_DISTANCE = 30.0;
70         private static final double MODEL_SCALE_FACTOR = 20.0;
71         private static final String DEFAULT_FONT_FILE = "crystal.ttf";
72
73
74         /**
75          * Constructor
76          * @param inApp App object
77          */
78         public PovExporter(App inApp)
79         {
80                 super(inApp);
81                 _track = inApp.getTrackInfo().getTrack();
82                 // Set default camera coordinates
83                 _cameraX = "17"; _cameraY = "13"; _cameraZ = "-20";
84         }
85
86         /** Get the name key */
87         public String getNameKey() {
88                 return "function.exportpov";
89         }
90
91         /**
92          * Set the coordinates for the camera (can be any scale)
93          * @param inX X coordinate of camera
94          * @param inY Y coordinate of camera
95          * @param inZ Z coordinate of camera
96          */
97         public void setCameraCoordinates(double inX, double inY, double inZ)
98         {
99                 // calculate distance from origin
100                 double cameraDist = Math.sqrt(inX*inX + inY*inY + inZ*inZ);
101                 if (cameraDist > 0.0)
102                 {
103                         _cameraX = NumberUtils.formatNumberUk(inX / cameraDist * DEFAULT_CAMERA_DISTANCE, 5);
104                         _cameraY = NumberUtils.formatNumberUk(inY / cameraDist * DEFAULT_CAMERA_DISTANCE, 5);
105                         // Careful! Need to convert from java3d (right-handed) to povray (left-handed) coordinate system!
106                         _cameraZ = NumberUtils.formatNumberUk(-inZ / cameraDist * DEFAULT_CAMERA_DISTANCE, 5);
107                 }
108         }
109
110
111         /**
112          * Show the dialog to select options and export file
113          */
114         public void begin()
115         {
116                 // Make dialog window to select inputs
117                 if (_dialog == null)
118                 {
119                         _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), true);
120                         _dialog.setLocationRelativeTo(_parentFrame);
121                         _dialog.getContentPane().add(makeDialogComponents());
122                 }
123                 // Get exaggeration factor from config
124                 final int exaggFactor = Config.getConfigInt(Config.KEY_HEIGHT_EXAGGERATION);
125                 if (exaggFactor > 0) {
126                         _altFactor = exaggFactor / 100.0;
127                 }
128
129                 // Set angles
130                 _cameraXField.setText(_cameraX);
131                 _cameraYField.setText(_cameraY);
132                 _cameraZField.setText(_cameraZ);
133                 _altitudeFactorField.setText("" + _altFactor);
134                 // Pass terrain and image def parameters (if any) to the panels
135                 if (_terrainDef != null) {
136                         _terrainPanel.initTerrainParameters(_terrainDef);
137                 }
138                 if (_imageDef != null) {
139                         _baseImagePanel.initImageParameters(_imageDef);
140                 }
141                 _baseImagePanel.updateBaseImageDetails();
142                 // Show dialog
143                 _dialog.pack();
144                 _dialog.setVisible(true);
145         }
146
147
148         /**
149          * Make the dialog components to select the export options
150          * @return Component holding gui elements
151          */
152         private Component makeDialogComponents()
153         {
154                 JPanel panel = new JPanel();
155                 panel.setLayout(new BorderLayout(4, 4));
156                 JLabel introLabel = new JLabel(I18nManager.getText("dialog.exportpov.text"));
157                 introLabel.setBorder(BorderFactory.createEmptyBorder(4, 4, 6, 4));
158                 panel.add(introLabel, BorderLayout.NORTH);
159                 // OK, Cancel buttons
160                 JPanel buttonPanel = new JPanel();
161                 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
162                 JButton okButton = new JButton(I18nManager.getText("button.ok"));
163                 okButton.addActionListener(new ActionListener() {
164                         public void actionPerformed(ActionEvent e)
165                         {
166                                 // Need to launch export in new thread
167                                 new Thread(new Runnable() {
168                                         public void run()
169                                         {
170                                                 doExport();
171                                                 _baseImagePanel.getGrouter().clearMapImage();
172                                         }
173                                 }).start();
174                                 _dialog.dispose();
175                         }
176                 });
177                 buttonPanel.add(okButton);
178                 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
179                 cancelButton.addActionListener(new ActionListener() {
180                         public void actionPerformed(ActionEvent e)
181                         {
182                                 _baseImagePanel.getGrouter().clearMapImage();
183                                 _dialog.dispose();
184                         }
185                 });
186                 buttonPanel.add(cancelButton);
187                 panel.add(buttonPanel, BorderLayout.SOUTH);
188
189                 // central panel
190                 JPanel centralPanel = new JPanel();
191                 centralPanel.setLayout(new GridLayout(0, 2, 10, 4));
192
193                 JLabel fontLabel = new JLabel(I18nManager.getText("dialog.exportpov.font"));
194                 fontLabel.setHorizontalAlignment(SwingConstants.TRAILING);
195                 centralPanel.add(fontLabel);
196                 String defaultFont = Config.getConfigString(Config.KEY_POVRAY_FONT);
197                 if (defaultFont == null || defaultFont.equals("")) {
198                         defaultFont = DEFAULT_FONT_FILE;
199                 }
200                 _fontName = new JTextField(defaultFont, 12);
201                 _fontName.setAlignmentX(Component.LEFT_ALIGNMENT);
202                 _fontName.addKeyListener(new DialogCloser(_dialog));
203                 centralPanel.add(_fontName);
204                 //coordinates of camera
205                 JLabel cameraXLabel = new JLabel(I18nManager.getText("dialog.exportpov.camerax"));
206                 cameraXLabel.setHorizontalAlignment(SwingConstants.TRAILING);
207                 centralPanel.add(cameraXLabel);
208                 _cameraXField = new JTextField("" + _cameraX);
209                 centralPanel.add(_cameraXField);
210                 JLabel cameraYLabel = new JLabel(I18nManager.getText("dialog.exportpov.cameray"));
211                 cameraYLabel.setHorizontalAlignment(SwingConstants.TRAILING);
212                 centralPanel.add(cameraYLabel);
213                 _cameraYField = new JTextField("" + _cameraY);
214                 centralPanel.add(_cameraYField);
215                 JLabel cameraZLabel = new JLabel(I18nManager.getText("dialog.exportpov.cameraz"));
216                 cameraZLabel.setHorizontalAlignment(SwingConstants.TRAILING);
217                 centralPanel.add(cameraZLabel);
218                 _cameraZField = new JTextField("" + _cameraZ);
219                 centralPanel.add(_cameraZField);
220                 // Altitude exaggeration
221                 JLabel altitudeCapLabel = new JLabel(I18nManager.getText("dialog.3d.altitudefactor"));
222                 altitudeCapLabel.setHorizontalAlignment(SwingConstants.TRAILING);
223                 centralPanel.add(altitudeCapLabel);
224                 _altitudeFactorField = new JTextField("1.0");
225                 centralPanel.add(_altitudeFactorField);
226
227                 // Radio buttons for style - balls on sticks or tubes
228                 JPanel stylePanel = new JPanel();
229                 stylePanel.setLayout(new GridLayout(0, 2, 10, 4));
230                 JLabel styleLabel = new JLabel(I18nManager.getText("dialog.exportpov.modelstyle"));
231                 styleLabel.setHorizontalAlignment(SwingConstants.TRAILING);
232                 stylePanel.add(styleLabel);
233                 JPanel radioPanel = new JPanel();
234                 radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
235                 _ballsAndSticksButton = new JRadioButton(I18nManager.getText("dialog.exportpov.ballsandsticks"));
236                 _ballsAndSticksButton.setSelected(false);
237                 radioPanel.add(_ballsAndSticksButton);
238                 JRadioButton tubesButton = new JRadioButton(I18nManager.getText("dialog.exportpov.tubesandwalls"));
239                 tubesButton.setSelected(true);
240                 radioPanel.add(tubesButton);
241                 ButtonGroup group = new ButtonGroup();
242                 group.add(_ballsAndSticksButton); group.add(tubesButton);
243                 stylePanel.add(radioPanel);
244
245                 // Panel for the base image (parent is null because we don't need callback)
246                 _baseImagePanel = new BaseImageDefinitionPanel(null, _dialog, _track);
247                 // Panel for the terrain definition
248                 _terrainPanel = new TerrainDefinitionPanel();
249
250                 // add these panels to the holder panel
251                 JPanel holderPanel = new JPanel();
252                 holderPanel.setLayout(new BorderLayout(5, 5));
253                 JPanel boxPanel = new JPanel();
254                 boxPanel.setLayout(new BoxLayout(boxPanel, BoxLayout.Y_AXIS));
255                 boxPanel.add(centralPanel);
256                 boxPanel.add(Box.createVerticalStrut(4));
257                 boxPanel.add(stylePanel);
258                 boxPanel.add(Box.createVerticalStrut(4));
259                 boxPanel.add(_terrainPanel);
260                 boxPanel.add(Box.createVerticalStrut(4));
261                 boxPanel.add(_baseImagePanel);
262                 holderPanel.add(boxPanel, BorderLayout.CENTER);
263
264                 panel.add(holderPanel, BorderLayout.CENTER);
265                 return panel;
266         }
267
268
269         /**
270          * Select the file and export data to it
271          */
272         private void doExport()
273         {
274                 // Copy camera coordinates
275                 _cameraX = checkCoordinate(_cameraXField.getText());
276                 _cameraY = checkCoordinate(_cameraYField.getText());
277                 _cameraZ = checkCoordinate(_cameraZField.getText());
278
279                 // OK pressed, so choose output file
280                 if (_fileChooser == null)
281                 {
282                         _fileChooser = new JFileChooser();
283                         _fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
284                         _fileChooser.setFileFilter(new GenericFileFilter("filetype.pov", new String[] {"pov"}));
285                         _fileChooser.setAcceptAllFileFilterUsed(false);
286                         // start from directory in config which should be set
287                         final String configDir = Config.getConfigString(Config.KEY_TRACK_DIR);
288                         if (configDir != null) {_fileChooser.setCurrentDirectory(new File(configDir));}
289                 }
290
291                 // Allow choose again if an existing file is selected
292                 boolean chooseAgain = false;
293                 do
294                 {
295                         chooseAgain = false;
296                         if (_fileChooser.showSaveDialog(_parentFrame) == JFileChooser.APPROVE_OPTION)
297                         {
298                                 // OK pressed and file chosen
299                                 File povFile = _fileChooser.getSelectedFile();
300                                 if (!povFile.getName().toLowerCase().endsWith(".pov"))
301                                 {
302                                         povFile = new File(povFile.getAbsolutePath() + ".pov");
303                                 }
304                                 final int nameLen = povFile.getName().length() - 4;
305                                 final File imageFile = new File(povFile.getParentFile(), povFile.getName().substring(0, nameLen) + "_base.png");
306                                 final File terrainFile = new File(povFile.getParentFile(), povFile.getName().substring(0, nameLen) + "_terrain.png");
307                                 final boolean imageExists = _baseImagePanel.getImageDefinition().getUseImage() && imageFile.exists();
308                                 final boolean terrainFileExists = _terrainPanel.getUseTerrain() && terrainFile.exists();
309
310                                 // Check if files exist and if necessary prompt for overwrite
311                                 Object[] buttonTexts = {I18nManager.getText("button.overwrite"), I18nManager.getText("button.cancel")};
312                                 if ((!povFile.exists() && !imageExists && !terrainFileExists)
313                                         || JOptionPane.showOptionDialog(_parentFrame,
314                                                 I18nManager.getText("dialog.save.overwrite.text"),
315                                                 I18nManager.getText("dialog.save.overwrite.title"), JOptionPane.YES_NO_OPTION,
316                                                 JOptionPane.WARNING_MESSAGE, null, buttonTexts, buttonTexts[1])
317                                         == JOptionPane.YES_OPTION)
318                                 {
319                                         // Export the file(s)
320                                         if (exportFiles(povFile, imageFile, terrainFile))
321                                         {
322                                                 // file saved - store directory in config for later
323                                                 Config.setConfigString(Config.KEY_TRACK_DIR, povFile.getParentFile().getAbsolutePath());
324                                                 // also store exaggeration and grid size
325                                                 Config.setConfigInt(Config.KEY_HEIGHT_EXAGGERATION, (int) (_altFactor * 100));
326                                                 if (_terrainPanel.getUseTerrain() && _terrainPanel.getGridSize() > 20) {
327                                                         Config.setConfigInt(Config.KEY_TERRAIN_GRID_SIZE, _terrainPanel.getGridSize());
328                                                 }
329                                         }
330                                         else
331                                         {
332                                                 // export failed so need to choose again
333                                                 chooseAgain = true;
334                                         }
335                                 }
336                                 else
337                                 {
338                                         // overwrite cancelled so need to choose again
339                                         chooseAgain = true;
340                                 }
341                         }
342                 } while (chooseAgain);
343         }
344
345
346         /**
347          * Export the data to the specified file(s)
348          * @param inPovFile File object to save pov file to
349          * @param inImageFile file object to save image to
350          * @param inTerrainFile file object to save terrain to
351          * @return true if successful
352          */
353         private boolean exportFiles(File inPovFile, File inImageFile, File inTerrainFile)
354         {
355                 FileWriter writer = null;
356                 // find out the line separator for this system
357                 final String lineSeparator = System.getProperty("line.separator");
358                 try
359                 {
360                         // create and scale model
361                         ThreeDModel model = new ThreeDModel(_track);
362                         model.setModelSize(MODEL_SCALE_FACTOR);
363                         try
364                         {
365                                 // try to use given altitude cap
366                                 double givenFactor = Double.parseDouble(_altitudeFactorField.getText());
367                                 if (givenFactor > 0.0) _altFactor = givenFactor;
368                         }
369                         catch (NumberFormatException nfe) { // parse failed, reset
370                                 _altitudeFactorField.setText("" + _altFactor);
371                         }
372                         model.setAltitudeFactor(_altFactor);
373
374                         // Write base image if necessary
375                         ImageDefinition imageDef = _baseImagePanel.getImageDefinition();
376                         boolean useImage = imageDef.getUseImage();
377                         if (useImage)
378                         {
379                                 // Get base image from grouter
380                                 MapSource mapSource = MapSourceLibrary.getSource(imageDef.getSourceIndex());
381                                 MapGrouter grouter = _baseImagePanel.getGrouter();
382                                 GroutedImage baseImage = grouter.getMapImage(_track, mapSource, imageDef.getZoom());
383                                 try
384                                 {
385                                         useImage = ImageIO.write(baseImage.getImage(), "png", inImageFile);
386                                 }
387                                 catch (IOException ioe) {
388                                         System.err.println("Can't write image: " + ioe.getClass().getName());
389                                         useImage = false;
390                                 }
391                                 if (!useImage) {
392                                         _app.showErrorMessage(getNameKey(), "dialog.exportpov.cannotmakebaseimage");
393                                 }
394                         }
395
396                         boolean useTerrain = _terrainPanel.getUseTerrain();
397                         if (useTerrain)
398                         {
399                                 TerrainHelper terrainHelper = new TerrainHelper(_terrainPanel.getGridSize());
400                                 // See if there's a previously saved terrain track we can reuse
401                                 TerrainDefinition terrainDef = new TerrainDefinition(_terrainPanel.getUseTerrain(), _terrainPanel.getGridSize());
402                                 Track terrainTrack = TerrainCache.getTerrainTrack(_app.getCurrentDataStatus(), terrainDef);
403                                 if (terrainTrack == null)
404                                 {
405                                         // Construct the terrain track according to these extents and the grid size
406                                         terrainTrack = terrainHelper.createGridTrack(_track);
407                                         // Get the altitudes from SRTM for all the points in the track
408                                         LookupSrtmFunction srtmLookup = (LookupSrtmFunction) FunctionLibrary.FUNCTION_LOOKUP_SRTM;
409                                         srtmLookup.begin(terrainTrack);
410                                         while (srtmLookup.isRunning())
411                                         {
412                                                 try {
413                                                         Thread.sleep(750);  // just polling in a wait loop isn't ideal but simple
414                                                 }
415                                                 catch (InterruptedException e) {}
416                                         }
417                                         // Fix the voids
418                                         terrainHelper.fixVoids(terrainTrack);
419
420                                         // Store this back in the cache, maybe we'll need it again
421                                         TerrainCache.storeTerrainTrack(terrainTrack, _app.getCurrentDataStatus(), terrainDef);
422                                 }
423
424                                 model.setTerrain(terrainTrack);
425                                 model.scale();
426
427                                 // Call TerrainHelper to write out the data from the model
428                                 terrainHelper.writeHeightMap(model, inTerrainFile);
429                         }
430                         else
431                         {
432                                 // No terrain required, so just scale the model as it is
433                                 model.scale();
434                         }
435
436                         // Create file and write basics
437                         writer = new FileWriter(inPovFile);
438                         writeStartOfFile(writer, lineSeparator, useImage ? inImageFile : null, useTerrain ? inTerrainFile : null);
439
440                         // write out points
441                         if (_ballsAndSticksButton.isSelected()) {
442                                 writeDataPointsBallsAndSticks(writer, model, lineSeparator);
443                         }
444                         else {
445                                 writeDataPointsTubesAndWalls(writer, model, lineSeparator);
446                         }
447
448                         // everything worked
449                         UpdateMessageBroker.informSubscribers(I18nManager.getText("confirm.save.ok1")
450                                  + " " + _track.getNumPoints() + " " + I18nManager.getText("confirm.save.ok2")
451                                  + " " + inPovFile.getAbsolutePath());
452                         return true;
453                 }
454                 catch (IOException ioe)
455                 {
456                         JOptionPane.showMessageDialog(_parentFrame, I18nManager.getText("error.save.failed") + " : " + ioe.getMessage(),
457                                 I18nManager.getText("error.save.dialogtitle"), JOptionPane.ERROR_MESSAGE);
458                 }
459                 finally
460                 {
461                         // close file ignoring exceptions
462                         try
463                         {
464                                 writer.close();
465                         }
466                         catch (Exception e) {}
467                 }
468                 return false;
469         }
470
471
472         /**
473          * Write the start of the Pov file, including base plane and lights
474          * @param inWriter Writer to use for writing file
475          * @param inLineSeparator line separator to use
476          * @param inImageFile image file to reference (or null if none)
477          * @param inTerrainFile terrain file to reference (or null if none)
478          * @throws IOException on file writing error
479          */
480         private void writeStartOfFile(FileWriter inWriter, String inLineSeparator, File inImageFile, File inTerrainFile)
481         throws IOException
482         {
483                 inWriter.write("// Pov file produced by GpsPrune - see http://gpsprune.activityworkshop.net/");
484                 inWriter.write(inLineSeparator);
485                 inWriter.write("#version 3.6;");
486                 inWriter.write(inLineSeparator);
487                 inWriter.write(inLineSeparator);
488                 // Select font based on user input
489                 String fontPath = _fontName.getText();
490                 if (fontPath == null || fontPath.equals(""))
491                 {
492                         fontPath = DEFAULT_FONT_FILE;
493                 }
494                 else {
495                         Config.setConfigString(Config.KEY_POVRAY_FONT, fontPath);
496                 }
497
498                 // Make the definition of the base plane depending on whether there's an image or not
499                 final boolean useImage = (inImageFile != null);
500                 final boolean useImageOnBox = useImage && (inTerrainFile == null);
501                 final String boxDefinition = (useImageOnBox ?
502                         "   <0, 0, 0>, <1, 1, 0.001>" + inLineSeparator
503                                 + "   pigment {image_map { png \"" + inImageFile.getName() + "\" map_type 0 interpolate 2 once } }" + inLineSeparator
504                                 + "   scale 20.0 rotate <90, 0, 0>" + inLineSeparator
505                                 + "   translate <-10.0, 0, -10.0>"
506                         : "   <-10.0, -0.15, -10.0>," + inLineSeparator
507                                 + "   <10.0, 0.0, 10.0>" + inLineSeparator
508                                 + "   pigment { color rgb <0.5 0.75 0.8> }");
509                 // TODO: Maybe could use the same geometry for the imageless case, would simplify code a bit
510
511                 // Definition of terrain shape if any
512                 final String terrainDefinition = makeTerrainString(inTerrainFile, inImageFile, inLineSeparator);
513
514                 // Set up output
515                 String[] outputLines = {
516                   "global_settings { ambient_light rgb <4, 4, 4> }", "",
517                   "// Background and camera",
518                   "background { color rgb <0, 0, 0> }",
519                   // camera position
520                   "camera {",
521                   "  location <" + _cameraX + ", " + _cameraY + ", " + _cameraZ + ">",
522                   "  look_at  <0, 0, 0>",
523                   "}", "",
524                 // global declares
525                   "// Global declares",
526                   "#declare point_rod =",
527                   "  cylinder {",
528                   "   <0, 0, 0>,",
529                   "   <0, 1, 0>,",
530                   "   0.15",
531                   "   open",
532                   "   texture {",
533                   "    pigment { color rgb <0.5 0.5 0.5> }",
534                   useImage ? "   } no_shadow" : "   }",
535                   "  }", "",
536                   // MAYBE: Export rods to POV?  How to store in data?
537                   "#declare waypoint_sphere =",
538                   "  sphere {",
539                   "   <0, 0, 0>, 0.4",
540                   "    texture {",
541                   "       pigment {color rgb <0.1 0.1 1.0>}",
542                   "       finish { phong 1 }",
543                   useImage ? "    } no_shadow" : "    }",
544                   "  }",
545                   "#declare track_sphere0 =",
546                   "  sphere {",
547                   "   <0, 0, 0>, 0.3", // size should depend on model size
548                   "   texture {",
549                   "      pigment {color rgb <0.1 0.6 0.1>}", // dark green
550                   "      finish { phong 1 }",
551                   "   }",
552                   " }",
553                   "#declare track_sphere1 =",
554                   "  sphere {",
555                   "   <0, 0, 0>, 0.3", // size should depend on model size
556                   "   texture {",
557                   "      pigment {color rgb <0.4 0.9 0.2>}", // green
558                   "      finish { phong 1 }",
559                   "   }",
560                   " }",
561                   "#declare track_sphere2 =",
562                   "  sphere {",
563                   "   <0, 0, 0>, 0.3", // size should depend on model size
564                   "   texture {",
565                   "      pigment {color rgb <0.7 0.8 0.2>}", // yellow
566                   "      finish { phong 1 }",
567                   "   }",
568                   " }",
569                   "#declare track_sphere3 =",
570                   "  sphere {",
571                   "   <0, 0, 0>, 0.3", // size should depend on model size
572                   "   texture {",
573                   "      pigment {color rgb <0.5 0.8 0.6>}", // greeny
574                   "      finish { phong 1 }",
575                   "   }",
576                   " }",
577                   "#declare track_sphere4 =",
578                   "  sphere {",
579                   "   <0, 0, 0>, 0.3", // size should depend on model size
580                   "   texture {",
581                   "      pigment {color rgb <0.2 0.9 0.9>}", // cyan
582                   "      finish { phong 1 }",
583                   "   }",
584                   " }",
585                   "#declare track_sphere5 =",
586                   "  sphere {",
587                   "   <0, 0, 0>, 0.3", // size should depend on model size
588                   "   texture {",
589                   "      pigment {color rgb <1.0 1.0 1.0>}", // white
590                   "      finish { phong 1 }",
591                   "   }",
592                   " }",
593                   "#declare track_sphere_t =",
594                   "  sphere {",
595                   "   <0, 0, 0>, 0.25", // size should depend on model size
596                   "   texture {",
597                   "      pigment {color rgb <0.6 1.0 0.2>}",
598                   "      finish { phong 1 }",
599                   "   } no_shadow",
600                   " }",
601                   "#declare wall_colour = rgbt <0.5, 0.5, 0.5, 0.3>;", "",
602                   "// Base plane",
603                   "box {",
604                   boxDefinition,
605                   "}", "",
606                   // terrain
607                   terrainDefinition,
608                 // write cardinals
609                   "// Cardinal letters N,S,E,W",
610                   "text {",
611                   "  ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.n") + "\" 0.3, 0",
612                   "  pigment { color rgb <1 1 1> }",
613                   "  translate <0, 0.2, 10.0>",
614                   "}",
615                   "text {",
616                   "  ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.s") + "\" 0.3, 0",
617                   "  pigment { color rgb <1 1 1> }",
618                   "  translate <0, 0.2, -10.0>",
619                   "}",
620                   "text {",
621                   "  ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.e") + "\" 0.3, 0",
622                   "  pigment { color rgb <1 1 1> }",
623                   "  translate <9.7, 0.2, 0>",
624                   "}",
625                   "text {",
626                   "  ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.w") + "\" 0.3, 0",
627                   "  pigment { color rgb <1 1 1> }",
628                   "  translate <-10.3, 0.2, 0>",
629                   "}", "",
630                   // MAYBE: Light positions should relate to model size
631                   "// lights",
632                   "light_source { <-1, 9, -4> color rgb <0.5 0.5 0.5>}",
633                   "light_source { <1, 6, -14> color rgb <0.6 0.6 0.6>}",
634                   "light_source { <11, 12, 8> color rgb <0.3 0.3 0.3>}",
635                   "",
636                 };
637                 // write strings to file
638                 int numLines = outputLines.length;
639                 for (int i=0; i<numLines; i++)
640                 {
641                         inWriter.write(outputLines[i]);
642                         inWriter.write(inLineSeparator);
643                 }
644         }
645
646         /**
647          * Make a description of the height_field object for the terrain, depending on terrain and image
648          * @param inTerrainFile terrain file, or null if none
649          * @param inImageFile image file, or null if none
650          * @param inLineSeparator line separator
651          * @return String for inserting into pov file
652          */
653         private static String makeTerrainString(File inTerrainFile, File inImageFile, String inLineSeparator)
654         {
655                 if (inTerrainFile == null) {return "";}
656                 StringBuilder sb = new StringBuilder();
657                 sb.append("//Terrain").append(inLineSeparator)
658                         .append("height_field {").append(inLineSeparator)
659                         .append("\tpng \"").append(inTerrainFile.getName()).append("\" smooth").append(inLineSeparator)
660                         .append("\tfinish {diffuse 0.7 phong 0.2}").append(inLineSeparator);
661                 if (inImageFile != null) {
662                         sb.append("\tpigment {image_map { png \"").append(inImageFile.getName()).append("\"  } rotate x*90}").append(inLineSeparator);
663                 }
664                 else {
665                         sb.append("\tpigment {color rgb <0.55 0.7 0.55> }").append(inLineSeparator);
666                 }
667                 sb.append("\tscale 20.0").append(inLineSeparator)
668                         .append("\ttranslate <-10.0, 0, -10.0>").append(inLineSeparator).append("}");
669                 return sb.toString();
670         }
671
672         /**
673          * Write out all the data points to the file in the balls-and-sticks style
674          * @param inWriter Writer to use for writing file
675          * @param inModel model object for getting data points
676          * @param inLineSeparator line separator to use
677          * @throws IOException on file writing error
678          */
679         private static void writeDataPointsBallsAndSticks(FileWriter inWriter, ThreeDModel inModel, String inLineSeparator)
680         throws IOException
681         {
682                 inWriter.write("// Data points:");
683                 inWriter.write(inLineSeparator);
684                 int numPoints = inModel.getNumPoints();
685                 for (int i=0; i<numPoints; i++)
686                 {
687                         // ball (different according to type)
688                         if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_WAYPOINT)
689                         {
690                                 // waypoint ball
691                                 inWriter.write("object { waypoint_sphere translate <" + inModel.getScaledHorizValue(i)
692                                         + "," + inModel.getScaledAltValue(i) + "," + inModel.getScaledVertValue(i) + "> }");
693                         }
694                         else
695                         {
696                                 // normal track point ball
697                                 inWriter.write("object { track_sphere" + checkHeightCode(inModel.getPointHeightCode(i))
698                                         + " translate <" + inModel.getScaledHorizValue(i) + "," + inModel.getScaledAltValue(i)
699                                         + "," + inModel.getScaledVertValue(i) + "> }");
700                         }
701                         inWriter.write(inLineSeparator);
702                         // vertical rod (if altitude positive)
703                         if (inModel.getScaledAltValue(i) > 0.0)
704                         {
705                                 inWriter.write("object { point_rod translate <" + inModel.getScaledHorizValue(i) + ",0,"
706                                         + inModel.getScaledVertValue(i) + "> scale <1," + inModel.getScaledAltValue(i) + ",1> }");
707                                 inWriter.write(inLineSeparator);
708                         }
709                 }
710                 inWriter.write(inLineSeparator);
711         }
712
713
714         /**
715          * Write out all the data points to the file in the tubes-and-walls style
716          * @param inWriter Writer to use for writing file
717          * @param inModel model object for getting data points
718          * @param inLineSeparator line separator to use
719          * @throws IOException on file writing error
720          */
721         private static void writeDataPointsTubesAndWalls(FileWriter inWriter, ThreeDModel inModel, String inLineSeparator)
722         throws IOException
723         {
724                 inWriter.write("// Data points:");
725                 inWriter.write(inLineSeparator);
726                 int numPoints = inModel.getNumPoints();
727                 // Loop over all points and write out waypoints as balls
728                 for (int i=0; i<numPoints; i++)
729                 {
730                         if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_WAYPOINT)
731                         {
732                                 // waypoint ball
733                                 inWriter.write("object { waypoint_sphere translate <" + inModel.getScaledHorizValue(i)
734                                         + "," + inModel.getScaledAltValue(i) + "," + inModel.getScaledVertValue(i) + "> }");
735                                 // vertical rod (if altitude positive)
736                                 if (inModel.getScaledAltValue(i) > 0.0)
737                                 {
738                                         inWriter.write(inLineSeparator);
739                                         inWriter.write("object { point_rod translate <" + inModel.getScaledHorizValue(i) + ",0,"
740                                                 + inModel.getScaledVertValue(i) + "> scale <1," + inModel.getScaledAltValue(i) + ",1> }");
741                                 }
742                                 inWriter.write(inLineSeparator);
743                         }
744                 }
745                 inWriter.write(inLineSeparator);
746
747                 // Loop over all the track segments
748                 ArrayList<ModelSegment> segmentList = getSegmentList(inModel);
749                 Iterator<ModelSegment> segmentIterator = segmentList.iterator();
750                 while (segmentIterator.hasNext())
751                 {
752                         ModelSegment segment = segmentIterator.next();
753                         int segLength = segment.getNumTrackPoints();
754
755                         // if the track segment is long enough, do a cubic spline sphere sweep
756                         if (segLength <= 1)
757                         {
758                                 // single point in segment - just draw sphere
759                                 int index = segment.getStartIndex();
760                                 inWriter.write("object { track_sphere_t"
761                                         + " translate <" + inModel.getScaledHorizValue(index) + "," + inModel.getScaledAltValue(index)
762                                         + "," + inModel.getScaledVertValue(index) + "> }");
763                                 // maybe draw some kind of polygon too or rod?
764                         }
765                         else
766                         {
767                                 writeSphereSweep(inWriter, inModel, segment, inLineSeparator);
768                         }
769
770                         // Write wall underneath segment
771                         if (segLength > 1)
772                         {
773                                 writePolygonWall(inWriter, inModel, segment, inLineSeparator);
774                         }
775                 }
776         }
777
778
779         /**
780          * Write out a single sphere sweep using either cubic spline or linear spline
781          * @param inWriter Writer to use for writing file
782          * @param inModel model object for getting data points
783          * @param inSegment model segment to draw
784          * @param inLineSeparator line separator to use
785          * @throws IOException on file writing error
786          */
787         private static void writeSphereSweep(FileWriter inWriter, ThreeDModel inModel, ModelSegment inSegment, String inLineSeparator)
788         throws IOException
789         {
790                 // 3d sphere sweep
791                 inWriter.write("// Sphere sweep:");
792                 inWriter.write(inLineSeparator);
793                 String splineType = inSegment.getNumTrackPoints() < 5?"linear_spline":"cubic_spline";
794                 inWriter.write("sphere_sweep { "); inWriter.write(splineType);
795                 inWriter.write(" " + inSegment.getNumTrackPoints() + ",");
796                 inWriter.write(inLineSeparator);
797                 // Loop over all points in this segment and write out sphere sweep
798                 for (int i=inSegment.getStartIndex(); i<=inSegment.getEndIndex(); i++)
799                 {
800                         if (inModel.getPointType(i) != ThreeDModel.POINT_TYPE_WAYPOINT)
801                         {
802                                 inWriter.write("  <" + inModel.getScaledHorizValue(i) + "," + inModel.getScaledAltValue(i)
803                                         + "," + inModel.getScaledVertValue(i) + ">, 0.25");
804                                 inWriter.write(inLineSeparator);
805                         }
806                 }
807                 inWriter.write("  tolerance 0.1");
808                 inWriter.write(inLineSeparator);
809                 inWriter.write("  texture { pigment {color rgb <0.6 1.0 0.2>}  finish {phong 1} }");
810                 inWriter.write(inLineSeparator);
811                 inWriter.write("  no_shadow");
812                 inWriter.write(inLineSeparator);
813                 inWriter.write("}");
814                 inWriter.write(inLineSeparator);
815         }
816
817
818         /**
819          * Write out a single polygon-based wall for the tubes-and-walls style
820          * @param inWriter Writer to use for writing file
821          * @param inModel model object for getting data points
822          * @param inSegment model segment to draw
823          * @param inLineSeparator line separator to use
824          * @throws IOException on file writing error
825          */
826         private static void writePolygonWall(FileWriter inWriter, ThreeDModel inModel, ModelSegment inSegment, String inLineSeparator)
827         throws IOException
828         {
829                 // wall
830                 inWriter.write(inLineSeparator);
831                 inWriter.write("// wall between sweep and floor:");
832                 inWriter.write(inLineSeparator);
833                 // Loop over all points in this segment again and write out polygons
834                 int prevIndex = -1;
835                 for (int i=inSegment.getStartIndex(); i<=inSegment.getEndIndex(); i++)
836                 {
837                         if (inModel.getPointType(i) != ThreeDModel.POINT_TYPE_WAYPOINT)
838                         {
839                                 if (prevIndex >= 0)
840                                 {
841                                         double xDiff = inModel.getScaledHorizValue(i) - inModel.getScaledHorizValue(prevIndex);
842                                         double yDiff = inModel.getScaledVertValue(i) - inModel.getScaledVertValue(prevIndex);
843                                         double dist = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
844                                         if (dist > 0)
845                                         {
846                                                 inWriter.write("polygon {");
847                                                 inWriter.write("  5, <" + inModel.getScaledHorizValue(prevIndex) + ", 0.0, " + inModel.getScaledVertValue(prevIndex) + ">,");
848                                                 inWriter.write(" <" + inModel.getScaledHorizValue(prevIndex) + ", " + inModel.getScaledAltValue(prevIndex) + ", "
849                                                         + inModel.getScaledVertValue(prevIndex) + ">,");
850                                                 inWriter.write(" <" + inModel.getScaledHorizValue(i) + ", " + inModel.getScaledAltValue(i) + ", "
851                                                         + inModel.getScaledVertValue(i) + ">,");
852                                                 inWriter.write(" <" + inModel.getScaledHorizValue(i) + ", 0.0, " + inModel.getScaledVertValue(i) + ">,");
853                                                 inWriter.write(" <" + inModel.getScaledHorizValue(prevIndex) + ", 0.0, " + inModel.getScaledVertValue(prevIndex) + ">");
854                                                 inWriter.write("  pigment { color wall_colour } no_shadow");
855                                                 inWriter.write("}");
856                                                 inWriter.write(inLineSeparator);
857                                         }
858                                 }
859                                 prevIndex = i;
860                         }
861                 }
862         }
863
864
865         /**
866          * @param inCode height code to check
867          * @return validated height code within range 0 to max
868          */
869         private static byte checkHeightCode(byte inCode)
870         {
871                 final byte maxHeightCode = 5;
872                 if (inCode < 0) return 0;
873                 if (inCode > maxHeightCode) return maxHeightCode;
874                 return inCode;
875         }
876
877
878         /**
879          * Check the given coordinate
880          * @param inString String entered by user
881          * @return validated String value
882          */
883         private static String checkCoordinate(String inString)
884         {
885                 double value = 0.0;
886                 try
887                 {
888                         value = Double.parseDouble(inString);
889                 }
890                 catch (Exception e) {} // ignore parse failures
891                 return "" + value;
892         }
893
894         /**
895          * Go through the points making a list of the segment starts and the number of track points in each segment
896          * @param inModel model containing data
897          * @return list of ModelSegment objects
898          */
899         private static ArrayList<ModelSegment> getSegmentList(ThreeDModel inModel)
900         {
901                 ArrayList<ModelSegment> segmentList = new ArrayList<ModelSegment>();
902                 if (inModel != null && inModel.getNumPoints() > 0)
903                 {
904                         ModelSegment currSegment = null;
905                         int numTrackPoints = 0;
906                         for (int i=0; i<inModel.getNumPoints(); i++)
907                         {
908                                 if (inModel.getPointType(i) != ThreeDModel.POINT_TYPE_WAYPOINT)
909                                 {
910                                         if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_SEGMENT_START || currSegment == null)
911                                         {
912                                                 // start of segment
913                                                 if (currSegment != null)
914                                                 {
915                                                         currSegment.setEndIndex(i-1);
916                                                         currSegment.setNumTrackPoints(numTrackPoints);
917                                                         segmentList.add(currSegment);
918                                                         numTrackPoints = 0;
919                                                 }
920                                                 currSegment = new ModelSegment(i);
921                                         }
922                                         numTrackPoints++;
923                                 }
924                         }
925                         // Add last segment to list
926                         if (currSegment != null && numTrackPoints > 0)
927                         {
928                                 currSegment.setEndIndex(inModel.getNumPoints()-1);
929                                 currSegment.setNumTrackPoints(numTrackPoints);
930                                 segmentList.add(currSegment);
931                         }
932                 }
933                 return segmentList;
934         }
935 }