summaryrefslogtreecommitdiff
path: root/trunk/software/host/src/org/reprap/RFO.java
blob: 4ca11763242d63673de5cd8c604b3d71cf93a2a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
/**
 * A .rfo file is a compressed archive containing multiple objects that are all to
 * be built in a RepRap machine at once.  See this web page:
 * 
 * http://reprap.org/bin/view/Main/MultipleMaterialsFiles
 * 
 * for details.
 * 
 * This is the class that handles .rfo files.
 */
package org.reprap;
// http://www.devx.com/tips/Tip/14049

import java.io.*;
import java.nio.channels.*;
import java.util.zip.*;
import java.util.Enumeration;


import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.helpers.DefaultHandler;


import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.vecmath.Matrix4d;
//import javax.vecmath.Matrix3d;
//import javax.vecmath.Point3d;
//import javax.vecmath.Tuple3d;
//import javax.vecmath.Vector3d;

import org.reprap.geometry.polygons.AllSTLsToBuild;
import org.reprap.utilities.Debug;
import org.reprap.gui.STLObject;

public class RFO 
{
	/**
	 * XML stack top.  If it gets 100 deep we're in trouble...
	 */
	static final int top = 100;
	
	/**
	 * Names of STL files in the compressed .rfo file
	 */
	static final String stlPrefix = "rfo-";
	static final String stlSuffix = ".stl";
	
	//**************************************************************************************
	//
	// XML file writing.  The legend file that ties everything together is XML.  This writes
	// it.
	
	class XMLOut
	{
		PrintStream XMLStream;
		String[] stack;
		int sp;
		
		/**
		 * Create an XML file called LegendFile starting with XML entry start.
		 * @param LegendFile
		 * @param start
		 */
		XMLOut(String LegendFile, String start)
		{
			FileOutputStream fileStream = null;
			try
			{
				fileStream = new FileOutputStream(LegendFile);
			} catch (Exception e)
			{
				Debug.e("XMLOut(): " + e);
			}
			XMLStream = new PrintStream(fileStream);
			stack = new String[top];
			sp = 0;
			push(start);
		}
		
		/**
		 * Start item s
		 * @param s
		 */
		void push(String s)
		{
			for(int i = 0; i < sp; i++)
				XMLStream.print(" ");
			XMLStream.println("<" + s + ">");
			int end = s.indexOf(" ");
			if(end < 0)
				stack[sp] = s;
			else
				stack[sp] = s.substring(0, end);
			sp++;
			if(sp >= top)
				Debug.e("RFO: XMLOut stack overflow on " + s);
		}
		
		/**
		 * Output a complete item s all in one go.
		 * @param s
		 */
		void write(String s)
		{
			for(int i = 0; i < sp; i++)
				XMLStream.print(" ");
			XMLStream.println("<" + s + "/>");
		}
		
		/**
		 * End the current item.
		 *
		 */
		void pop()
		{
			sp--;
			for(int i = 0; i < sp; i++)
				XMLStream.print(" ");
			if(sp < 0)
				Debug.e("RFO: XMLOut stack underflow.");
			XMLStream.println("</" + stack[sp] + ">");
		}
		
		/**
		 * Wind it up.
		 *
		 */
		void close()
		{
			while(sp > 0)
				pop();
			XMLStream.close();
		}
	}
	
	//**************************************************************************************
	//
	// XML file reading.  This reads the legend file.
	
	class XMLIn extends DefaultHandler
	{
		/**
		 * The rfo that we are reading in
		 */
		private RFO rfo;
		
		/**
		 * The STL being read
		 */
		private STLObject stl;
		
		/**
		 * The first of a list of STLs being read.
		 */
		private STLObject firstSTL;
		/**
		 * The current XML item
		 */
		private String element;
		
		/**
		 * File location for reading (eg for an input STL file).
		 */
		private String location;
		
		/**
		 * What type of file (Only STLs supported at the moment).
		 */
		private String filetype;
		
		/**
		 * The name of the material (i.e. extruder) that this item is made from.
		 */
		private String material;
		
		/**
		 * Transfom matrix to get an item in the right place.
		 */
		private double[] mElements;
		private Transform3D transform;
		
		private int rowNumber = 0;
		
		/**
		 * Open up legendFile and use it to build RFO rfo.
		 * @param legendFile
		 * @param r
		 */
		XMLIn(String legendFile, RFO r)
		{
			super();
			rfo = r;
			element = "";
			location = "";
			filetype = "";
			material = "";
			mElements = new double[16];
			setMToIdentity();			
			
			XMLReader xr = null;
			try
			{
				xr = XMLReaderFactory.createXMLReader();
			} catch (Exception e)
			{
				Debug.e("XMLIn() 1: " + e);
			}
			
			xr.setContentHandler(this);
			xr.setErrorHandler(this);
			try
			{
				xr.parse(new InputSource(legendFile));
			} catch (Exception e)
			{
				Debug.e("XMLIn() 2: " + e);
			}

		}

		/**
		 * Initialise the matrix to the identity matrix.
		 *
		 */
		private void setMToIdentity()
		{
			for(rowNumber = 0; rowNumber < 4; rowNumber++)
				for(int column = 0; column < 4; column++)
				{
					if(rowNumber == column)
						mElements[rowNumber*4 + column] = 1;
					else
						mElements[rowNumber*4 + column] = 0;
				}
			transform = new Transform3D(mElements);
			rowNumber = 0;
		}
		////////////////////////////////////////////////////////////////////
		// Event handlers.  These are callbacks for the XML parser.
		////////////////////////////////////////////////////////////////////


		/**
		 * Begin the XML document - no action needed.
		 */
		public void startDocument ()
		{
			//System.out.println("Start document");
		}


		/**
		 * End the XML document - no action needed.
		 */
		public void endDocument ()
		{
			//System.out.println("End document");
		}


		/**
		 * Start an element
		 */
		public void startElement (String uri, String name,
				String qName, org.xml.sax.Attributes atts)
		{
			if (uri.equals(""))
				element = qName;
			else
				element = name;
			//System.out.print(element);
			
			// What element is it?
			
			if(element.equalsIgnoreCase("reprap-fab-at-home-build"))
			{
				
			} else if(element.equalsIgnoreCase("object"))
			{
				stl = new STLObject();
				firstSTL = null;
			} else  if(element.equalsIgnoreCase("files"))
			{
				
			} else if(element.equalsIgnoreCase("file"))
			{
				location = atts.getValue("location");
				filetype = atts.getValue("filetype");
				material = atts.getValue("material");
				if(!filetype.equalsIgnoreCase("application/sla"))
					Debug.e("XMLIn.startElement(): unreconised object file type (should be \"application/sla\"): " + filetype);
			} else if(element.equalsIgnoreCase("transform3D"))
			{
				setMToIdentity();
			} else if(element.equalsIgnoreCase("row"))
			{
				for(int column = 0; column < 4; column++)
					mElements[rowNumber*4 + column] = Double.parseDouble(atts.getValue("m" + rowNumber + column));
			} else
			{
				Debug.e("XMLIn.startElement(): unreconised RFO element: " + element);
			}
		}

		/**
		 * End an element
		 */
		public void endElement (String uri, String name, String qName)
		{
			if (uri.equals(""))
				element = qName;
			else
				element = name;
			if(element.equalsIgnoreCase("reprap-fab-at-home-build"))
			{
				
			} else if(element.equalsIgnoreCase("object"))
			{
				stl.setTransform(transform);
				rfo.astl.add(stl);
			} else  if(element.equalsIgnoreCase("files"))
			{
				
			} else if(element.equalsIgnoreCase("file"))
			{
				org.reprap.Attributes att = stl.addSTL("file:" + rfoDir + location, null, Preferences.unselectedApp(), firstSTL);
				if(firstSTL == null)
					firstSTL = stl;
				att.setMaterial(material);
				location = "";
				filetype = "";
				material = "";

			} else if(element.equalsIgnoreCase("transform3D"))
			{
				if(rowNumber != 4)
					Debug.e("XMLIn.endElement(): incomplete Transform3D matrix - last row number is not 4: " + rowNumber);
				transform = new Transform3D(mElements);
			} else if(element.equalsIgnoreCase("row"))
			{
				rowNumber++;
			} else
			{
				Debug.e("XMLIn.endElement(): unreconised RFO element: " + element);
			}
		}

		/**
		 * Nothing to do for characters in between.
		 */
		public void characters (char ch[], int start, int length)
		{
//			for (int i = start; i < start + length; i++) 
//				System.out.print(ch[i]);
//			System.out.println();
		}

	}
	
	//**************************************************************************************
	//
	// Start of RFO handling
	
	private static final String legendName = "legend.xml";
	
	/**
	 * The name of the RFO file.
	 */
	private String fileName;
	
	/**
	 * The directory in which it is.
	 */
	private String path;
	
	/**
	 * The temporary directory
	 */
	private String tempDir;
	
	/**
	 * The location of the temporary RFO directory
	 */
	private String  rfoDir;
	
	/**
	 * The unique temporary directory name
	 */
	private String uniqueName;
	
	/**
	 * The collection of objects being written out or read in.
	 */
	private AllSTLsToBuild astl;
	
	/**
	 * The XML output for the legend file.
	 */
	private XMLOut xml;
	
	/**
	 * The constructor is the same whether we're reading or writing.  fn is where to put or get the
	 * rfo file from.  as is all the things to write; set that null when reading.
	 * @param fn
	 * @param as
	 */
	private RFO(String fn, AllSTLsToBuild as)
	{
		astl = as;
		int sepIndex = fn.lastIndexOf(File.separator);
		int fIndex = fn.indexOf("file:");
		fileName = fn.substring(sepIndex + 1, fn.length());
		if(sepIndex >= 0)
		{
			if(fIndex >= 0)
				path = fn.substring(fIndex + 5, sepIndex + 1);
			else
				path = fn.substring(0, sepIndex + 1);
		} else
			path = "";
		
		uniqueName = "rfo" + Long.toString(System.nanoTime());

		tempDir = System.getProperty("java.io.tmpdir") + File.separator + uniqueName;
		
		File rfod = new File(tempDir);
		if(!rfod.mkdir())
			throw new RuntimeException(tempDir);
		tempDir += File.separator;
		rfoDir = tempDir + "rfo";
		rfod = new File(rfoDir);
		if(!rfod.mkdir())
			throw new RuntimeException(rfoDir);
		rfoDir += File.separator;
	}
	

	public static boolean recursiveDelete(File fileOrDir)
	{
	    if(fileOrDir.isDirectory())
	    {
	        // recursively delete contents
	        for(File innerFile: fileOrDir.listFiles())
	        {
	            if(!recursiveDelete(innerFile))
	            {
	                return false;
	            }
	        }
	    }

	    return fileOrDir.delete();
	}



	//****************************************************************************
	//
	// .rfo writing
	
	/**
	 * Copy a file from one place to another
	 */
	private static void copyFile(File in, File out)
	{
		try
		{
			FileChannel inChannel = new	FileInputStream(in).getChannel();
			FileChannel outChannel = new FileOutputStream(out).getChannel();
			inChannel.transferTo(0, inChannel.size(), outChannel);
			inChannel.close();
			outChannel.close();			
		} catch (Exception e)
		{
			Debug.e("RFO.copyFile(): " + e);
		}

	}		
	
	/**
	 * Copy a file from one place to another.
	 * @param from
	 * @param to
	 */
	private static void copyFile(String from, String to)
	{
		File inputFile;
	    File outputFile;
		int fIndex = from.indexOf("file:");
		int tIndex = to.indexOf("file:");
		if(fIndex < 0)
			inputFile = new File(from);
		else
			inputFile = new File(from.substring(fIndex + 5, from.length()));
		if(tIndex < 0)
			outputFile = new File(to);
		else
			outputFile = new File(to.substring(tIndex + 5, to.length())); 
		copyFile(inputFile, outputFile);		
	}
	
	/**
	 * Create the name of STL file number i
	 * @param i
	 * @return
	 */
	private String stlName(int i)
	{
		return stlPrefix + i + stlSuffix;
	}
	
	/**
	 * Copy each unique STL file to the temporary directory.  Files used more
	 * than once are only copied once.
	 *
	 */
	private void copySTLs()
	{
		int u = 0;
		for(int i = 0; i < astl.size(); i++)
		{
			for(int subMod1 = 0; subMod1 < astl.get(i).size(); subMod1++)
			{
				String s = astl.get(i).fileItCameFrom(subMod1);
				astl.get(i).setUnique(subMod1, u);
				for(int j = 0; j < i; j++)
				{
					for(int subMod2 = 0; subMod2 < astl.get(j).size(); subMod2++)
					{
						if(s.equals(astl.get(j).fileItCameFrom(subMod2)))
						{
							astl.get(i).setUnique(subMod1, astl.get(j).getUnique(subMod2));
							break;
						}
					}
				}
				if(astl.get(i).getUnique(subMod1) == u)
				{
					copyFile(s, rfoDir + stlName(u));
					u++;
				}
			}
		}	
	}
	
	/**
	 * Write a 4x4 homogeneous transform in XML format.
	 * @param trans
	 */
	private void writeTransform(TransformGroup trans)
	{
		Transform3D t = new Transform3D();
		Matrix4d m = new Matrix4d();
		trans.getTransform(t);
		t.get(m);
		xml.push("transform3D");
		 xml.write("row m00=\"" + m.m00 + "\" m01=\"" + m.m01 + "\" m02=\"" + m.m02 + "\" m03=\"" + m.m03 + "\"");
		 xml.write("row m10=\"" + m.m10 + "\" m11=\"" + m.m11 + "\" m12=\"" + m.m12 + "\" m13=\"" + m.m13 + "\"");
		 xml.write("row m20=\"" + m.m20 + "\" m21=\"" + m.m21 + "\" m22=\"" + m.m22 + "\" m23=\"" + m.m23 + "\"");
		 xml.write("row m30=\"" + m.m30 + "\" m31=\"" + m.m31 + "\" m32=\"" + m.m32 + "\" m33=\"" + m.m33 + "\"");
		xml.pop();
	}
	
	/**
	 * Create the legend file
	 *
	 */
	private void createLegend()
	{
		xml = new XMLOut(rfoDir + legendName, "reprap-fab-at-home-build version=\"0.1\"");
		for(int i = 0; i < astl.size(); i++)
		{
			xml.push("object name=\"object-" + i + "\"");
			 xml.push("files");
			  STLObject stlo = astl.get(i);
			  for(int subObj = 0; subObj < stlo.size(); subObj++)
			  {
				  xml.push("file location=\"" + stlName(stlo.getUnique(subObj)) + "\" filetype=\"application/sla\" material=\"" + 
						  stlo.attributes(subObj).getMaterial() + "\"");
				  xml.pop();
			  }
			 xml.pop();
			 writeTransform(stlo.trans());
			xml.pop();
		}
		xml.close();
	}
	
	/**
	 * The entire temporary directory with the legend file and ann the STLs is complete.
	 * Compress it into the required rfo file using zip.  Note we delete the temporary files as we
	 * go along, ending up by deleting the directory containing them.
	 *
	 */
	private void compress()
	{
		try
		{
			ZipOutputStream rfoFile = new ZipOutputStream(new FileOutputStream(path + fileName)); 
			File dirToZip = new File(rfoDir); 
			String[] fileList = dirToZip.list(); 
			byte[] buffer = new byte[4096]; 
			int bytesIn = 0; 

			for(int i=0; i<fileList.length; i++) 
			{ 
				File f = new File(dirToZip, fileList[i]); 
				FileInputStream fis = new FileInputStream(f); 
				String zEntry = f.getPath();
				//System.out.println("\n" + zEntry);
				int start = zEntry.indexOf(uniqueName);
				zEntry = zEntry.substring(start + uniqueName.length() + 1, zEntry.length());
				//System.out.println(tempDir);
				//System.out.println(zEntry + "\n");
				ZipEntry entry = new ZipEntry(zEntry); 
				rfoFile.putNextEntry(entry); 
				while((bytesIn = fis.read(buffer)) != -1) 
					rfoFile.write(buffer, 0, bytesIn); 
				fis.close();
			}
			rfoFile.close();
		} catch (Exception e)
		{
			Debug.e("RFO.compress(): " + e);
		}
	}
	
	/**
	 * This is what gets called to write an rfo file.  It saves all the parts of allSTL in rfo file fn.
	 * @param fn
	 * @param allSTL
	 */
	public static void save(String fn, AllSTLsToBuild allSTL)
	{
		if(!fn.endsWith(".rfo"))
			fn += ".rfo";
		RFO rfo = new RFO(fn, allSTL);
		rfo.copySTLs();
		rfo.createLegend();
		rfo.compress();
		File t = new File(rfo.tempDir);
		recursiveDelete(t);
	}
	
	//******************************************************************************************
	//
	// .rfo reading
	
	/**
	 * Arrghhh!!!!
	 */
	private String processSeparators(String is)
	{
		String result = "";
		for(int i = 0; i < is.length(); i++)
		{
			if(is.charAt(i) == '\\')
			{
				if(File.separator.charAt(0) == '/')
					result += '/';
				else
					result += '\\';
			} else if(is.charAt(i) == '/')
			{
				if(File.separator.charAt(0) == '\\')
					result += '\\';
				else
					result += '/';
			} else
				result += is.charAt(i);
		}
		
		return result;
	}
	
	/**
	 * This uncompresses the zip that is the rfo file into the temporary directory.
	 */
	private void unCompress()
	{
		try
		{
			byte[] buffer = new byte[4096];
			int bytesIn;
			ZipFile rfoFile = new ZipFile(path + fileName);
			Enumeration<? extends ZipEntry> allFiles = rfoFile.entries();
			while(allFiles.hasMoreElements())
			{
				ZipEntry ze = (ZipEntry)allFiles.nextElement();
				InputStream is = rfoFile.getInputStream(ze);
				String fName = processSeparators(ze.getName());
				File element = new File(tempDir + fName);
				org.reprap.Main.ftd.add(element);
				FileOutputStream os = new FileOutputStream(element);
				while((bytesIn = is.read(buffer)) != -1) 
					os.write(buffer, 0, bytesIn);
				os.close();
			}
		} catch (Exception e)
		{
			Debug.e("RFO.unCompress(): " + e);
		}
	}
	
	/**
	 * This reads the legend file and does what it says.
	 *
	 */
	private void interpretLegend()
	{
		@SuppressWarnings("unused")
		XMLIn xi = new XMLIn(rfoDir + legendName, this);
	}
	
	/**
	 * This is what gets called to read an rfo file from filename fn.
	 * @param fn
	 * @return
	 */
	public static AllSTLsToBuild load(String fn)
	{
		if(!fn.endsWith(".rfo"))
			fn += ".rfo";
		RFO rfo = new RFO(fn, null);
		File rfod = new File(rfo.tempDir);
		org.reprap.Main.ftd.add(rfod);
		rfod = new File(rfo.rfoDir);
		org.reprap.Main.ftd.add(rfod);
		
		rfo.astl = new AllSTLsToBuild();
		rfo.unCompress();
		try
		{
			rfo.interpretLegend();
		} catch (Exception e)
		{
			Debug.e("RFO.load(): exception - " + e.toString());
		}
		
		// Tidy up - delete the temporary files and the directory
		// containing them.
		
//		File td = new File(rfo.rfoDir);
//		String[] fileList = td.list(); 
//		for(int i=0; i<fileList.length; i++) 
//		{ 
//			File f = new File(rfo.rfoDir, fileList[i]);
//			if(!f.delete())
//				Debug.e("RFO.AllSTLsToBuild(): Can't delete file: " + fileList[i]);
//		}
//		if(!td.delete())
//			Debug.e("RFO.AllSTLsToBuild(): Can't delete file: " + rfo.rfoDir);
		return rfo.astl;
	}
}