]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/save/PovExporter.java
19e4485c66bf0e09ec576793804bdf88c4187591
[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
325                                                 Config.setConfigInt(Config.KEY_HEIGHT_EXAGGERATION, (int) (_altFactor * 100));
326                                         }
327                                         else
328                                         {
329                                                 // export failed so need to choose again
330                                                 chooseAgain = true;
331                                         }
332                                 }
333                                 else
334                                 {
335                                         // overwrite cancelled so need to choose again
336                                         chooseAgain = true;
337                                 }
338                         }
339                 } while (chooseAgain);
340         }
341
342
343         /**
344          * Export the data to the specified file(s)
345          * @param inPovFile File object to save pov file to
346          * @param inImageFile file object to save image to
347          * @param inTerrainFile file object to save terrain to
348          * @return true if successful
349          */
350         private boolean exportFiles(File inPovFile, File inImageFile, File inTerrainFile)
351         {
352                 FileWriter writer = null;
353                 // find out the line separator for this system
354                 final String lineSeparator = System.getProperty("line.separator");
355                 try
356                 {
357                         // create and scale model
358                         ThreeDModel model = new ThreeDModel(_track);
359                         model.setModelSize(MODEL_SCALE_FACTOR);
360                         try
361                         {
362                                 // try to use given altitude cap
363                                 double givenFactor = Double.parseDouble(_altitudeFactorField.getText());
364                                 if (givenFactor > 0.0) _altFactor = givenFactor;
365                         }
366                         catch (NumberFormatException nfe) { // parse failed, reset
367                                 _altitudeFactorField.setText("" + _altFactor);
368                         }
369                         model.setAltitudeFactor(_altFactor);
370
371                         // Write base image if necessary
372                         ImageDefinition imageDef = _baseImagePanel.getImageDefinition();
373                         boolean useImage = imageDef.getUseImage();
374                         if (useImage)
375                         {
376                                 // Get base image from grouter
377                                 MapSource mapSource = MapSourceLibrary.getSource(imageDef.getSourceIndex());
378                                 MapGrouter grouter = _baseImagePanel.getGrouter();
379                                 GroutedImage baseImage = grouter.getMapImage(_track, mapSource, imageDef.getZoom());
380                                 try
381                                 {
382                                         useImage = ImageIO.write(baseImage.getImage(), "png", inImageFile);
383                                 }
384                                 catch (IOException ioe) {
385                                         System.err.println("Can't write image: " + ioe.getClass().getName());
386                                         useImage = false;
387                                 }
388                                 if (!useImage) {
389                                         _app.showErrorMessage(getNameKey(), "dialog.exportpov.cannotmakebaseimage");
390                                 }
391                         }
392
393                         boolean useTerrain = _terrainPanel.getUseTerrain();
394                         if (useTerrain)
395                         {
396                                 TerrainHelper terrainHelper = new TerrainHelper(_terrainPanel.getGridSize());
397                                 // See if there's a previously saved terrain track we can reuse
398                                 TerrainDefinition terrainDef = new TerrainDefinition(_terrainPanel.getUseTerrain(), _terrainPanel.getGridSize());
399                                 Track terrainTrack = TerrainCache.getTerrainTrack(_app.getCurrentDataStatus(), terrainDef);
400                                 if (terrainTrack == null)
401                                 {
402                                         // Construct the terrain track according to these extents and the grid size
403                                         terrainTrack = terrainHelper.createGridTrack(_track);
404                                         // Get the altitudes from SRTM for all the points in the track
405                                         LookupSrtmFunction srtmLookup = (LookupSrtmFunction) FunctionLibrary.FUNCTION_LOOKUP_SRTM;
406                                         srtmLookup.begin(terrainTrack);
407                                         while (srtmLookup.isRunning())
408                                         {
409                                                 try {
410                                                         Thread.sleep(750);  // just polling in a wait loop isn't ideal but simple
411                                                 }
412                                                 catch (InterruptedException e) {}
413                                         }
414                                         // Fix the voids
415                                         terrainHelper.fixVoids(terrainTrack);
416
417                                         // Store this back in the cache, maybe we'll need it again
418                                         TerrainCache.storeTerrainTrack(terrainTrack, _app.getCurrentDataStatus(), terrainDef);
419                                 }
420
421                                 model.setTerrain(terrainTrack);
422                                 model.scale();
423
424                                 // Call TerrainHelper to write out the data from the model
425                                 terrainHelper.writeHeightMap(model, inTerrainFile);
426                         }
427                         else
428                         {
429                                 // No terrain required, so just scale the model as it is
430                                 model.scale();
431                         }
432
433                         // Create file and write basics
434                         writer = new FileWriter(inPovFile);
435                         writeStartOfFile(writer, lineSeparator, useImage ? inImageFile : null, useTerrain ? inTerrainFile : null);
436
437                         // write out points
438                         if (_ballsAndSticksButton.isSelected()) {
439                                 writeDataPointsBallsAndSticks(writer, model, lineSeparator);
440                         }
441                         else {
442                                 writeDataPointsTubesAndWalls(writer, model, lineSeparator);
443                         }
444
445                         // everything worked
446                         UpdateMessageBroker.informSubscribers(I18nManager.getText("confirm.save.ok1")
447                                  + " " + _track.getNumPoints() + " " + I18nManager.getText("confirm.save.ok2")
448                                  + " " + inPovFile.getAbsolutePath());
449                         return true;
450                 }
451                 catch (IOException ioe)
452                 {
453                         JOptionPane.showMessageDialog(_parentFrame, I18nManager.getText("error.save.failed") + " : " + ioe.getMessage(),
454                                 I18nManager.getText("error.save.dialogtitle"), JOptionPane.ERROR_MESSAGE);
455                 }
456                 finally
457                 {
458                         // close file ignoring exceptions
459                         try
460                         {
461                                 writer.close();
462                         }
463                         catch (Exception e) {}
464                 }
465                 return false;
466         }
467
468
469         /**
470          * Write the start of the Pov file, including base plane and lights
471          * @param inWriter Writer to use for writing file
472          * @param inLineSeparator line separator to use
473          * @param inImageFile image file to reference (or null if none)
474          * @param inTerrainFile terrain file to reference (or null if none)
475          * @throws IOException on file writing error
476          */
477         private void writeStartOfFile(FileWriter inWriter, String inLineSeparator, File inImageFile, File inTerrainFile)
478         throws IOException
479         {
480                 inWriter.write("// Pov file produced by GpsPrune - see http://gpsprune.activityworkshop.net/");
481                 inWriter.write(inLineSeparator);
482                 inWriter.write("#version 3.6;");
483                 inWriter.write(inLineSeparator);
484                 inWriter.write(inLineSeparator);
485                 // Select font based on user input
486                 String fontPath = _fontName.getText();
487                 if (fontPath == null || fontPath.equals(""))
488                 {
489                         fontPath = DEFAULT_FONT_FILE;
490                 }
491                 else {
492                         Config.setConfigString(Config.KEY_POVRAY_FONT, fontPath);
493                 }
494
495                 // Make the definition of the base plane depending on whether there's an image or not
496                 final boolean useImage = (inImageFile != null);
497                 final boolean useImageOnBox = useImage && (inTerrainFile == null);
498                 final String boxDefinition = (useImageOnBox ?
499                         "   <0, 0, 0>, <1, 1, 0.001>" + inLineSeparator
500                                 + "   pigment {image_map { png \"" + inImageFile.getName() + "\" map_type 0 interpolate 2 once } }" + inLineSeparator
501                                 + "   scale 20.0 rotate <90, 0, 0>" + inLineSeparator
502                                 + "   translate <-10.0, 0, -10.0>"
503                         : "   <-10.0, -0.15, -10.0>," + inLineSeparator
504                                 + "   <10.0, 0.0, 10.0>" + inLineSeparator
505                                 + "   pigment { color rgb <0.5 0.75 0.8> }");
506                 // TODO: Maybe could use the same geometry for the imageless case, would simplify code a bit
507
508                 // Definition of terrain shape if any
509                 final String terrainDefinition = makeTerrainString(inTerrainFile, inImageFile, inLineSeparator);
510
511                 // Set up output
512                 String[] outputLines = {
513                   "global_settings { ambient_light rgb <4, 4, 4> }", "",
514                   "// Background and camera",
515                   "background { color rgb <0, 0, 0> }",
516                   // camera position
517                   "camera {",
518                   "  location <" + _cameraX + ", " + _cameraY + ", " + _cameraZ + ">",
519                   "  look_at  <0, 0, 0>",
520                   "}", "",
521                 // global declares
522                   "// Global declares",
523                   "#declare point_rod =",
524                   "  cylinder {",
525                   "   <0, 0, 0>,",
526                   "   <0, 1, 0>,",
527                   "   0.15",
528                   "   open",
529                   "   texture {",
530                   "    pigment { color rgb <0.5 0.5 0.5> }",
531                   useImage ? "   } no_shadow" : "   }",
532                   "  }", "",
533                   // MAYBE: Export rods to POV?  How to store in data?
534                   "#declare waypoint_sphere =",
535                   "  sphere {",
536                   "   <0, 0, 0>, 0.4",
537                   "    texture {",
538                   "       pigment {color rgb <0.1 0.1 1.0>}",
539                   "       finish { phong 1 }",
540                   useImage ? "    } no_shadow" : "    }",
541                   "  }",
542                   "#declare track_sphere0 =",
543                   "  sphere {",
544                   "   <0, 0, 0>, 0.3", // size should depend on model size
545                   "   texture {",
546                   "      pigment {color rgb <0.1 0.6 0.1>}", // dark green
547                   "      finish { phong 1 }",
548                   "   }",
549                   " }",
550                   "#declare track_sphere1 =",
551                   "  sphere {",
552                   "   <0, 0, 0>, 0.3", // size should depend on model size
553                   "   texture {",
554                   "      pigment {color rgb <0.4 0.9 0.2>}", // green
555                   "      finish { phong 1 }",
556                   "   }",
557                   " }",
558                   "#declare track_sphere2 =",
559                   "  sphere {",
560                   "   <0, 0, 0>, 0.3", // size should depend on model size
561                   "   texture {",
562                   "      pigment {color rgb <0.7 0.8 0.2>}", // yellow
563                   "      finish { phong 1 }",
564                   "   }",
565                   " }",
566                   "#declare track_sphere3 =",
567                   "  sphere {",
568                   "   <0, 0, 0>, 0.3", // size should depend on model size
569                   "   texture {",
570                   "      pigment {color rgb <0.5 0.8 0.6>}", // greeny
571                   "      finish { phong 1 }",
572                   "   }",
573                   " }",
574                   "#declare track_sphere4 =",
575                   "  sphere {",
576                   "   <0, 0, 0>, 0.3", // size should depend on model size
577                   "   texture {",
578                   "      pigment {color rgb <0.2 0.9 0.9>}", // cyan
579                   "      finish { phong 1 }",
580                   "   }",
581                   " }",
582                   "#declare track_sphere5 =",
583                   "  sphere {",
584                   "   <0, 0, 0>, 0.3", // size should depend on model size
585                   "   texture {",
586                   "      pigment {color rgb <1.0 1.0 1.0>}", // white
587                   "      finish { phong 1 }",
588                   "   }",
589                   " }",
590                   "#declare track_sphere_t =",
591                   "  sphere {",
592                   "   <0, 0, 0>, 0.25", // size should depend on model size
593                   "   texture {",
594                   "      pigment {color rgb <0.6 1.0 0.2>}",
595                   "      finish { phong 1 }",
596                   "   } no_shadow",
597                   " }",
598                   "#declare wall_colour = rgbt <0.5, 0.5, 0.5, 0.3>;", "",
599                   "// Base plane",
600                   "box {",
601                   boxDefinition,
602                   "}", "",
603                   // terrain
604                   terrainDefinition,
605                 // write cardinals
606                   "// Cardinal letters N,S,E,W",
607                   "text {",
608                   "  ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.n") + "\" 0.3, 0",
609                   "  pigment { color rgb <1 1 1> }",
610                   "  translate <0, 0.2, 10.0>",
611                   "}",
612                   "text {",
613                   "  ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.s") + "\" 0.3, 0",
614                   "  pigment { color rgb <1 1 1> }",
615                   "  translate <0, 0.2, -10.0>",
616                   "}",
617                   "text {",
618                   "  ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.e") + "\" 0.3, 0",
619                   "  pigment { color rgb <1 1 1> }",
620                   "  translate <9.7, 0.2, 0>",
621                   "}",
622                   "text {",
623                   "  ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.w") + "\" 0.3, 0",
624                   "  pigment { color rgb <1 1 1> }",
625                   "  translate <-10.3, 0.2, 0>",
626                   "}", "",
627                   // MAYBE: Light positions should relate to model size
628                   "// lights",
629                   "light_source { <-1, 9, -4> color rgb <0.5 0.5 0.5>}",
630                   "light_source { <1, 6, -14> color rgb <0.6 0.6 0.6>}",
631                   "light_source { <11, 12, 8> color rgb <0.3 0.3 0.3>}",
632                   "",
633                 };
634                 // write strings to file
635                 int numLines = outputLines.length;
636                 for (int i=0; i<numLines; i++)
637                 {
638                         inWriter.write(outputLines[i]);
639                         inWriter.write(inLineSeparator);
640                 }
641         }
642
643         /**
644          * Make a description of the height_field object for the terrain, depending on terrain and image
645          * @param inTerrainFile terrain file, or null if none
646          * @param inImageFile image file, or null if none
647          * @param inLineSeparator line separator
648          * @return String for inserting into pov file
649          */
650         private static String makeTerrainString(File inTerrainFile, File inImageFile, String inLineSeparator)
651         {
652                 if (inTerrainFile == null) {return "";}
653                 StringBuilder sb = new StringBuilder();
654                 sb.append("//Terrain").append(inLineSeparator)
655                         .append("height_field {").append(inLineSeparator)
656                         .append("\tpng \"").append(inTerrainFile.getName()).append("\" smooth").append(inLineSeparator)
657                         .append("\tfinish {diffuse 0.7 phong 0.2}").append(inLineSeparator);
658                 if (inImageFile != null) {
659                         sb.append("\tpigment {image_map { png \"").append(inImageFile.getName()).append("\"  } rotate x*90}").append(inLineSeparator);
660                 }
661                 else {
662                         sb.append("\tpigment {color rgb <0.55 0.7 0.55> }").append(inLineSeparator);
663                 }
664                 sb.append("\tscale 20.0").append(inLineSeparator)
665                         .append("\ttranslate <-10.0, 0, -10.0>").append(inLineSeparator).append("}");
666                 return sb.toString();
667         }
668
669         /**
670          * Write out all the data points to the file in the balls-and-sticks style
671          * @param inWriter Writer to use for writing file
672          * @param inModel model object for getting data points
673          * @param inLineSeparator line separator to use
674          * @throws IOException on file writing error
675          */
676         private static void writeDataPointsBallsAndSticks(FileWriter inWriter, ThreeDModel inModel, String inLineSeparator)
677         throws IOException
678         {
679                 inWriter.write("// Data points:");
680                 inWriter.write(inLineSeparator);
681                 int numPoints = inModel.getNumPoints();
682                 for (int i=0; i<numPoints; i++)
683                 {
684                         // ball (different according to type)
685                         if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_WAYPOINT)
686                         {
687                                 // waypoint ball
688                                 inWriter.write("object { waypoint_sphere translate <" + inModel.getScaledHorizValue(i)
689                                         + "," + inModel.getScaledAltValue(i) + "," + inModel.getScaledVertValue(i) + "> }");
690                         }
691                         else
692                         {
693                                 // normal track point ball
694                                 inWriter.write("object { track_sphere" + checkHeightCode(inModel.getPointHeightCode(i))
695                                         + " translate <" + inModel.getScaledHorizValue(i) + "," + inModel.getScaledAltValue(i)
696                                         + "," + inModel.getScaledVertValue(i) + "> }");
697                         }
698                         inWriter.write(inLineSeparator);
699                         // vertical rod (if altitude positive)
700                         if (inModel.getScaledAltValue(i) > 0.0)
701                         {
702                                 inWriter.write("object { point_rod translate <" + inModel.getScaledHorizValue(i) + ",0,"
703                                         + inModel.getScaledVertValue(i) + "> scale <1," + inModel.getScaledAltValue(i) + ",1> }");
704                                 inWriter.write(inLineSeparator);
705                         }
706                 }
707                 inWriter.write(inLineSeparator);
708         }
709
710
711         /**
712          * Write out all the data points to the file in the tubes-and-walls style
713          * @param inWriter Writer to use for writing file
714          * @param inModel model object for getting data points
715          * @param inLineSeparator line separator to use
716          * @throws IOException on file writing error
717          */
718         private static void writeDataPointsTubesAndWalls(FileWriter inWriter, ThreeDModel inModel, String inLineSeparator)
719         throws IOException
720         {
721                 inWriter.write("// Data points:");
722                 inWriter.write(inLineSeparator);
723                 int numPoints = inModel.getNumPoints();
724                 // Loop over all points and write out waypoints as balls
725                 for (int i=0; i<numPoints; i++)
726                 {
727                         if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_WAYPOINT)
728                         {
729                                 // waypoint ball
730                                 inWriter.write("object { waypoint_sphere translate <" + inModel.getScaledHorizValue(i)
731                                         + "," + inModel.getScaledAltValue(i) + "," + inModel.getScaledVertValue(i) + "> }");
732                                 // vertical rod (if altitude positive)
733                                 if (inModel.getScaledAltValue(i) > 0.0)
734                                 {
735                                         inWriter.write(inLineSeparator);
736                                         inWriter.write("object { point_rod translate <" + inModel.getScaledHorizValue(i) + ",0,"
737                                                 + inModel.getScaledVertValue(i) + "> scale <1," + inModel.getScaledAltValue(i) + ",1> }");
738                                 }
739                                 inWriter.write(inLineSeparator);
740                         }
741                 }
742                 inWriter.write(inLineSeparator);
743
744                 // Loop over all the track segments
745                 ArrayList<ModelSegment> segmentList = getSegmentList(inModel);
746                 Iterator<ModelSegment> segmentIterator = segmentList.iterator();
747                 while (segmentIterator.hasNext())
748                 {
749                         ModelSegment segment = segmentIterator.next();
750                         int segLength = segment.getNumTrackPoints();
751
752                         // if the track segment is long enough, do a cubic spline sphere sweep
753                         if (segLength <= 1)
754                         {
755                                 // single point in segment - just draw sphere
756                                 int index = segment.getStartIndex();
757                                 inWriter.write("object { track_sphere_t"
758                                         + " translate <" + inModel.getScaledHorizValue(index) + "," + inModel.getScaledAltValue(index)
759                                         + "," + inModel.getScaledVertValue(index) + "> }");
760                                 // maybe draw some kind of polygon too or rod?
761                         }
762                         else
763                         {
764                                 writeSphereSweep(inWriter, inModel, segment, inLineSeparator);
765                         }
766
767                         // Write wall underneath segment
768                         if (segLength > 1)
769                         {
770                                 writePolygonWall(inWriter, inModel, segment, inLineSeparator);
771                         }
772                 }
773         }
774
775
776         /**
777          * Write out a single sphere sweep using either cubic spline or linear spline
778          * @param inWriter Writer to use for writing file
779          * @param inModel model object for getting data points
780          * @param inSegment model segment to draw
781          * @param inLineSeparator line separator to use
782          * @throws IOException on file writing error
783          */
784         private static void writeSphereSweep(FileWriter inWriter, ThreeDModel inModel, ModelSegment inSegment, String inLineSeparator)
785         throws IOException
786         {
787                 // 3d sphere sweep
788                 inWriter.write("// Sphere sweep:");
789                 inWriter.write(inLineSeparator);
790                 String splineType = inSegment.getNumTrackPoints() < 5?"linear_spline":"cubic_spline";
791                 inWriter.write("sphere_sweep { "); inWriter.write(splineType);
792                 inWriter.write(" " + inSegment.getNumTrackPoints() + ",");
793                 inWriter.write(inLineSeparator);
794                 // Loop over all points in this segment and write out sphere sweep
795                 for (int i=inSegment.getStartIndex(); i<=inSegment.getEndIndex(); i++)
796                 {
797                         if (inModel.getPointType(i) != ThreeDModel.POINT_TYPE_WAYPOINT)
798                         {
799                                 inWriter.write("  <" + inModel.getScaledHorizValue(i) + "," + inModel.getScaledAltValue(i)
800                                         + "," + inModel.getScaledVertValue(i) + ">, 0.25");
801                                 inWriter.write(inLineSeparator);
802                         }
803                 }
804                 inWriter.write("  tolerance 0.1");
805                 inWriter.write(inLineSeparator);
806                 inWriter.write("  texture { pigment {color rgb <0.6 1.0 0.2>}  finish {phong 1} }");
807                 inWriter.write(inLineSeparator);
808                 inWriter.write("  no_shadow");
809                 inWriter.write(inLineSeparator);
810                 inWriter.write("}");
811                 inWriter.write(inLineSeparator);
812         }
813
814
815         /**
816          * Write out a single polygon-based wall for the tubes-and-walls style
817          * @param inWriter Writer to use for writing file
818          * @param inModel model object for getting data points
819          * @param inSegment model segment to draw
820          * @param inLineSeparator line separator to use
821          * @throws IOException on file writing error
822          */
823         private static void writePolygonWall(FileWriter inWriter, ThreeDModel inModel, ModelSegment inSegment, String inLineSeparator)
824         throws IOException
825         {
826                 // wall
827                 inWriter.write(inLineSeparator);
828                 inWriter.write("// wall between sweep and floor:");
829                 inWriter.write(inLineSeparator);
830                 // Loop over all points in this segment again and write out polygons
831                 int prevIndex = -1;
832                 for (int i=inSegment.getStartIndex(); i<=inSegment.getEndIndex(); i++)
833                 {
834                         if (inModel.getPointType(i) != ThreeDModel.POINT_TYPE_WAYPOINT)
835                         {
836                                 if (prevIndex >= 0)
837                                 {
838                                         double xDiff = inModel.getScaledHorizValue(i) - inModel.getScaledHorizValue(prevIndex);
839                                         double yDiff = inModel.getScaledVertValue(i) - inModel.getScaledVertValue(prevIndex);
840                                         double dist = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
841                                         if (dist > 0)
842                                         {
843                                                 inWriter.write("polygon {");
844                                                 inWriter.write("  5, <" + inModel.getScaledHorizValue(prevIndex) + ", 0.0, " + inModel.getScaledVertValue(prevIndex) + ">,");
845                                                 inWriter.write(" <" + inModel.getScaledHorizValue(prevIndex) + ", " + inModel.getScaledAltValue(prevIndex) + ", "
846                                                         + inModel.getScaledVertValue(prevIndex) + ">,");
847                                                 inWriter.write(" <" + inModel.getScaledHorizValue(i) + ", " + inModel.getScaledAltValue(i) + ", "
848                                                         + inModel.getScaledVertValue(i) + ">,");
849                                                 inWriter.write(" <" + inModel.getScaledHorizValue(i) + ", 0.0, " + inModel.getScaledVertValue(i) + ">,");
850                                                 inWriter.write(" <" + inModel.getScaledHorizValue(prevIndex) + ", 0.0, " + inModel.getScaledVertValue(prevIndex) + ">");
851                                                 inWriter.write("  pigment { color wall_colour } no_shadow");
852                                                 inWriter.write("}");
853                                                 inWriter.write(inLineSeparator);
854                                         }
855                                 }
856                                 prevIndex = i;
857                         }
858                 }
859         }
860
861
862         /**
863          * @param inCode height code to check
864          * @return validated height code within range 0 to max
865          */
866         private static byte checkHeightCode(byte inCode)
867         {
868                 final byte maxHeightCode = 5;
869                 if (inCode < 0) return 0;
870                 if (inCode > maxHeightCode) return maxHeightCode;
871                 return inCode;
872         }
873
874
875         /**
876          * Check the given coordinate
877          * @param inString String entered by user
878          * @return validated String value
879          */
880         private static String checkCoordinate(String inString)
881         {
882                 double value = 0.0;
883                 try
884                 {
885                         value = Double.parseDouble(inString);
886                 }
887                 catch (Exception e) {} // ignore parse failures
888                 return "" + value;
889         }
890
891         /**
892          * Go through the points making a list of the segment starts and the number of track points in each segment
893          * @param inModel model containing data
894          * @return list of ModelSegment objects
895          */
896         private static ArrayList<ModelSegment> getSegmentList(ThreeDModel inModel)
897         {
898                 ArrayList<ModelSegment> segmentList = new ArrayList<ModelSegment>();
899                 if (inModel != null && inModel.getNumPoints() > 0)
900                 {
901                         ModelSegment currSegment = null;
902                         int numTrackPoints = 0;
903                         for (int i=0; i<inModel.getNumPoints(); i++)
904                         {
905                                 if (inModel.getPointType(i) != ThreeDModel.POINT_TYPE_WAYPOINT)
906                                 {
907                                         if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_SEGMENT_START || currSegment == null)
908                                         {
909                                                 // start of segment
910                                                 if (currSegment != null)
911                                                 {
912                                                         currSegment.setEndIndex(i-1);
913                                                         currSegment.setNumTrackPoints(numTrackPoints);
914                                                         segmentList.add(currSegment);
915                                                         numTrackPoints = 0;
916                                                 }
917                                                 currSegment = new ModelSegment(i);
918                                         }
919                                         numTrackPoints++;
920                                 }
921                         }
922                         // Add last segment to list
923                         if (currSegment != null && numTrackPoints > 0)
924                         {
925                                 currSegment.setEndIndex(inModel.getNumPoints()-1);
926                                 currSegment.setNumTrackPoints(numTrackPoints);
927                                 segmentList.add(currSegment);
928                         }
929                 }
930                 return segmentList;
931         }
932 }