Merge branch 'upstream' into debian
[debian/openrocket] / core / src / net / sf / openrocket / gui / print / DesignReport.java
1 /*
2  * DesignReport.java
3  */
4 package net.sf.openrocket.gui.print;
5
6 import java.awt.Graphics2D;
7 import java.io.IOException;
8 import java.text.DecimalFormat;
9
10 import net.sf.openrocket.document.OpenRocketDocument;
11 import net.sf.openrocket.document.Simulation;
12 import net.sf.openrocket.gui.figureelements.FigureElement;
13 import net.sf.openrocket.gui.figureelements.RocketInfo;
14 import net.sf.openrocket.gui.scalefigure.RocketPanel;
15 import net.sf.openrocket.gui.util.SwingPreferences;
16 import net.sf.openrocket.logging.LogHelper;
17 import net.sf.openrocket.masscalc.BasicMassCalculator;
18 import net.sf.openrocket.masscalc.MassCalculator;
19 import net.sf.openrocket.masscalc.MassCalculator.MassCalcType;
20 import net.sf.openrocket.motor.Motor;
21 import net.sf.openrocket.rocketcomponent.Configuration;
22 import net.sf.openrocket.rocketcomponent.MotorMount;
23 import net.sf.openrocket.rocketcomponent.Rocket;
24 import net.sf.openrocket.rocketcomponent.RocketComponent;
25 import net.sf.openrocket.rocketcomponent.Stage;
26 import net.sf.openrocket.simulation.FlightData;
27 import net.sf.openrocket.simulation.exception.SimulationException;
28 import net.sf.openrocket.startup.Application;
29 import net.sf.openrocket.unit.Unit;
30 import net.sf.openrocket.unit.UnitGroup;
31 import net.sf.openrocket.util.Chars;
32 import net.sf.openrocket.util.Coordinate;
33
34 import com.itextpdf.text.Document;
35 import com.itextpdf.text.DocumentException;
36 import com.itextpdf.text.Element;
37 import com.itextpdf.text.Paragraph;
38 import com.itextpdf.text.Rectangle;
39 import com.itextpdf.text.pdf.BaseFont;
40 import com.itextpdf.text.pdf.DefaultFontMapper;
41 import com.itextpdf.text.pdf.PdfContentByte;
42 import com.itextpdf.text.pdf.PdfPCell;
43 import com.itextpdf.text.pdf.PdfPTable;
44 import com.itextpdf.text.pdf.PdfWriter;
45
46 /**
47  * <pre>
48  * #  Title # Section describing the rocket in general without motors
49  * # Section describing the rocket in general without motors
50  * <p/>
51  * design name
52  * empty mass & CG
53  * CP position
54  * CP position at 5 degree AOA (or similar)
55  * number of stages
56  * parachute/streamer sizes
57  * max. diameter (caliber)
58  * velocity at exit of rail/rod
59  * minimum safe velocity reached in x inches/cm
60  * <p/>
61  * # Section for each motor configuration
62  * <p/>
63  * a summary of the motors, e.g. 3xC6-0; B4-6
64  * a list of the motors including the manufacturer, designation (maybe also info like burn time, grams of propellant,
65  * total impulse)
66  * total grams of propellant
67  * total impulse
68  * takeoff weight
69  * CG and CP position, stability margin
70  * predicted flight altitude, max. velocity and max. acceleration
71  * predicted velocity at chute deployment
72  * predicted descent rate
73  * Thrust to Weight Ratio of each stage
74  * <p/>
75  * </pre>
76  */
77 public class DesignReport {
78         
79         /**
80          * The logger.
81          */
82         private static final LogHelper log = Application.getLogger();
83         
84         /**
85          * The OR Document.
86          */
87         private OpenRocketDocument rocketDocument;
88         
89         /**
90          * A panel used for rendering of the design diagram.
91          */
92         final RocketPanel panel;
93         
94         /**
95          * The iText document.
96          */
97         protected Document document;
98         
99         /** The displayed strings. */
100         private static final String STAGES = "Stages: ";
101         private static final String MASS_WITH_MOTORS = "Mass (with motors): ";
102         private static final String MASS_WITH_MOTOR = "Mass (with motor): ";
103         private static final String MASS_EMPTY = "Mass (Empty): ";
104         private static final String STABILITY = "Stability: ";
105         private static final String CG = "CG: ";
106         private static final String CP = "CP: ";
107         private static final String MOTOR = "Motor";
108         private static final String AVG_THRUST = "Avg Thrust";
109         private static final String BURN_TIME = "Burn Time";
110         private static final String MAX_THRUST = "Max Thrust";
111         private static final String TOTAL_IMPULSE = "Total Impulse";
112         private static final String THRUST_TO_WT = "Thrust to Wt";
113         private static final String PROPELLANT_WT = "Propellant Wt";
114         private static final String SIZE = "Size";
115         private static final String ALTITUDE = "Altitude";
116         private static final String FLIGHT_TIME = "Flight Time";
117         private static final String TIME_TO_APOGEE = "Time to Apogee";
118         private static final String VELOCITY_OFF_PAD = "Velocity off Pad";
119         private static final String MAX_VELOCITY = "Max Velocity";
120         private static final String DEPLOYMENT_VELOCITY = "Velocity at Deployment";
121         private static final String LANDING_VELOCITY = "Landing Velocity";
122         private static final String ROCKET_DESIGN = "Rocket Design";
123         private static final double GRAVITY_CONSTANT = 9.80665d;
124         
125         /**
126          * Constructor.
127          *
128          * @param theRocDoc the OR document
129          * @param theIDoc   the iText document
130          */
131         public DesignReport(OpenRocketDocument theRocDoc, Document theIDoc) {
132                 document = theIDoc;
133                 rocketDocument = theRocDoc;
134                 panel = new RocketPanel(rocketDocument);
135         }
136         
137         /**
138          * Main entry point.  Prints the rocket drawing and design data.
139          *
140          * @param writer a direct byte writer
141          */
142         public void writeToDocument(PdfWriter writer) {
143                 if (writer == null) {
144                         return;
145                 }
146                 com.itextpdf.text.Rectangle pageSize = document.getPageSize();
147                 int pageImageableWidth = (int) pageSize.getWidth() - (int) pageSize.getBorderWidth() * 2;
148                 int pageImageableHeight = (int) pageSize.getHeight() / 2 - (int) pageSize.getBorderWidthTop();
149                 
150                 PrintUtilities.addText(document, PrintUtilities.BIG_BOLD, ROCKET_DESIGN);
151                 
152                 Rocket rocket = rocketDocument.getRocket();
153                 final Configuration configuration = rocket.getDefaultConfiguration().clone();
154                 configuration.setAllStages();
155                 PdfContentByte canvas = writer.getDirectContent();
156                 
157                 final PrintFigure figure = new PrintFigure(configuration);
158                 
159                 FigureElement cp = panel.getExtraCP();
160                 FigureElement cg = panel.getExtraCG();
161                 RocketInfo text = panel.getExtraText();
162                 
163                 double scale = paintRocketDiagram(pageImageableWidth, pageImageableHeight, canvas, figure, cp, cg);
164                 
165                 canvas.beginText();
166                 try {
167                         canvas.setFontAndSize(BaseFont.createFont(PrintUtilities.NORMAL.getFamilyname(), BaseFont.CP1252,
168                                                                                                                 BaseFont.EMBEDDED), PrintUtilities.NORMAL_FONT_SIZE);
169                 } catch (DocumentException e) {
170                         log.error("Could not set font.", e);
171                 } catch (IOException e) {
172                         log.error("Could not create font.", e);
173                 }
174                 int figHeightPts = (int) (PrintUnit.METERS.toPoints(figure.getFigureHeight()) * 0.4 * (scale / PrintUnit.METERS
175                                 .toPoints(1)));
176                 final int diagramHeight = pageImageableHeight * 2 - 70 - (figHeightPts);
177                 canvas.moveText(document.leftMargin() + pageSize.getBorderWidthLeft(), diagramHeight);
178                 canvas.moveTextWithLeading(0, -16);
179                 
180                 float initialY = canvas.getYTLM();
181                 
182                 canvas.showText(rocketDocument.getRocket().getName());
183                 
184                 canvas.newlineShowText(STAGES);
185                 canvas.showText("" + rocket.getStageCount());
186                 
187
188                 if (configuration.hasMotors()) {
189                         if (configuration.getStageCount() > 1) {
190                                 canvas.newlineShowText(MASS_WITH_MOTORS);
191                         } else {
192                                 canvas.newlineShowText(MASS_WITH_MOTOR);
193                         }
194                 } else {
195                         canvas.newlineShowText(MASS_EMPTY);
196                 }
197                 canvas.showText(text.getMass(UnitGroup.UNITS_MASS.getDefaultUnit()));
198                 
199                 canvas.newlineShowText(STABILITY);
200                 canvas.showText(text.getStability());
201                 
202                 canvas.newlineShowText(CG);
203                 canvas.showText(text.getCg());
204                 
205                 canvas.newlineShowText(CP);
206                 canvas.showText(text.getCp());
207                 canvas.endText();
208                 
209                 try {
210                         //Move the internal pointer of the document below that of what was just written using the direct byte buffer.
211                         Paragraph paragraph = new Paragraph();
212                         float finalY = canvas.getYTLM();
213                         int heightOfDiagramAndText = (int) (pageSize.getHeight() - (finalY - initialY + diagramHeight));
214                         
215                         paragraph.setSpacingAfter(heightOfDiagramAndText);
216                         document.add(paragraph);
217                         
218                         String[] motorIds = rocket.getMotorConfigurationIDs();
219                         
220                         for (int j = 0; j < motorIds.length; j++) {
221                                 String motorId = motorIds[j];
222                                 if (motorId != null) {
223                                         PdfPTable parent = new PdfPTable(2);
224                                         parent.setWidthPercentage(100);
225                                         parent.setHorizontalAlignment(Element.ALIGN_LEFT);
226                                         parent.setSpacingBefore(0);
227                                         parent.setWidths(new int[] { 1, 3 });
228                                         int leading = 0;
229                                         //The first motor config is always null.  Skip it and the top-most motor, then set the leading.
230                                         if (j > 1) {
231                                                 leading = 25;
232                                         }
233                                         addFlightData(rocket, motorId, parent, leading);
234                                         addMotorData(rocket, motorId, parent);
235                                         document.add(parent);
236                                 }
237                         }
238                 } catch (DocumentException e) {
239                         log.error("Could not modify document.", e);
240                 }
241         }
242         
243         
244         /**
245          * Paint a diagram of the rocket into the PDF document.
246          *
247          * @param thePageImageableWidth  the number of points in the width of the page available for drawing
248          * @param thePageImageableHeight the number of points in the height of the page available for drawing
249          * @param theCanvas              the direct byte writer
250          * @param theFigure              the print figure
251          * @param theCp                  the center of pressure figure element
252          * @param theCg                  the center of gravity figure element
253          *
254          * @return the scale of the diagram
255          */
256         private double paintRocketDiagram(final int thePageImageableWidth, final int thePageImageableHeight,
257                                                                                 final PdfContentByte theCanvas, final PrintFigure theFigure,
258                                                                                 final FigureElement theCp, final FigureElement theCg) {
259                 theFigure.clearAbsoluteExtra();
260                 theFigure.clearRelativeExtra();
261                 theFigure.addRelativeExtra(theCp);
262                 theFigure.addRelativeExtra(theCg);
263                 theFigure.updateFigure();
264                 
265                 double scale =
266                                 (thePageImageableWidth * 2.2) / theFigure.getFigureWidth();
267                 
268                 theFigure.setScale(scale);
269                 /*
270                  * page dimensions are in points-per-inch, which, in Java2D, are the same as pixels-per-inch; thus we don't need any conversion
271                  */
272                 theFigure.setSize(thePageImageableWidth, thePageImageableHeight);
273                 theFigure.updateFigure();
274                 
275
276                 final DefaultFontMapper mapper = new DefaultFontMapper();
277                 Graphics2D g2d = theCanvas.createGraphics(thePageImageableWidth, thePageImageableHeight * 2, mapper);
278                 g2d.translate(20, 120);
279                 
280                 g2d.scale(0.4d, 0.4d);
281                 theFigure.paint(g2d);
282                 g2d.dispose();
283                 return scale;
284         }
285         
286         /**
287          * Add the motor data for a motor configuration to the table.
288          *
289          * @param rocket        the rocket
290          * @param motorId       the motor ID to output
291          * @param parent        the parent to which the motor data will be added
292          */
293         private void addMotorData(Rocket rocket, String motorId, final PdfPTable parent) {
294                 
295                 PdfPTable motorTable = new PdfPTable(8);
296                 motorTable.setWidthPercentage(68);
297                 motorTable.setHorizontalAlignment(Element.ALIGN_LEFT);
298                 
299                 final PdfPCell motorCell = ITextHelper.createCell(MOTOR, PdfPCell.BOTTOM);
300                 final int mPad = 10;
301                 motorCell.setPaddingLeft(mPad);
302                 motorTable.addCell(motorCell);
303                 motorTable.addCell(ITextHelper.createCell(AVG_THRUST, PdfPCell.BOTTOM));
304                 motorTable.addCell(ITextHelper.createCell(BURN_TIME, PdfPCell.BOTTOM));
305                 motorTable.addCell(ITextHelper.createCell(MAX_THRUST, PdfPCell.BOTTOM));
306                 motorTable.addCell(ITextHelper.createCell(TOTAL_IMPULSE, PdfPCell.BOTTOM));
307                 motorTable.addCell(ITextHelper.createCell(THRUST_TO_WT, PdfPCell.BOTTOM));
308                 motorTable.addCell(ITextHelper.createCell(PROPELLANT_WT, PdfPCell.BOTTOM));
309                 motorTable.addCell(ITextHelper.createCell(SIZE, PdfPCell.BOTTOM));
310                 
311                 DecimalFormat ttwFormat = new DecimalFormat("0.00");
312                 
313                 MassCalculator massCalc = new BasicMassCalculator();
314                 
315                 Configuration config = new Configuration(rocket);
316                 config.setMotorConfigurationID(motorId);
317                 
318                 int totalMotorCount = 0;
319                 double totalPropMass = 0;
320                 double totalImpulse = 0;
321                 double totalTTW = 0;
322                 
323                 int stage = 0;
324                 double stageMass = 0;
325                 
326                 boolean topBorder = false;
327                 for (RocketComponent c : rocket) {
328                         
329                         if (c instanceof Stage) {
330                                 config.setToStage(stage);
331                                 stage++;
332                                 stageMass = massCalc.getCG(config, MassCalcType.LAUNCH_MASS).weight;
333                                 // Calculate total thrust-to-weight from only lowest stage motors
334                                 totalTTW = 0;
335                                 topBorder = true;
336                         }
337                         
338                         if (c instanceof MotorMount && ((MotorMount) c).isMotorMount()) {
339                                 MotorMount mount = (MotorMount) c;
340                                 
341                                 if (mount.isMotorMount() && mount.getMotor(motorId) != null) {
342                                         Motor motor = mount.getMotor(motorId);
343                                         int motorCount = c.toAbsolute(Coordinate.NUL).length;
344                                         
345
346                                         int border = Rectangle.NO_BORDER;
347                                         if (topBorder) {
348                                                 border = Rectangle.TOP;
349                                                 topBorder = false;
350                                         }
351                                         
352                                         String name = motor.getDesignation();
353                                         if (motorCount > 1) {
354                                                 name += " (" + Chars.TIMES + motorCount + ")";
355                                         }
356                                         
357                                         final PdfPCell motorVCell = ITextHelper.createCell(name, border);
358                                         motorVCell.setPaddingLeft(mPad);
359                                         motorTable.addCell(motorVCell);
360                                         motorTable.addCell(ITextHelper.createCell(
361                                                         UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(motor.getAverageThrustEstimate()), border));
362                                         motorTable.addCell(ITextHelper.createCell(
363                                                         UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit().toStringUnit(motor.getBurnTimeEstimate()), border));
364                                         motorTable.addCell(ITextHelper.createCell(
365                                                         UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(motor.getMaxThrustEstimate()), border));
366                                         motorTable.addCell(ITextHelper.createCell(
367                                                         UnitGroup.UNITS_IMPULSE.getDefaultUnit().toStringUnit(motor.getTotalImpulseEstimate()), border));
368                                         
369                                         double ttw = motor.getAverageThrustEstimate() / (stageMass * GRAVITY_CONSTANT);
370                                         motorTable.addCell(ITextHelper.createCell(
371                                                         ttwFormat.format(ttw) + ":1", border));
372                                         
373                                         double propMass = (motor.getLaunchCG().weight - motor.getEmptyCG().weight);
374                                         motorTable.addCell(ITextHelper.createCell(
375                                                         UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(propMass), border));
376                                         
377                                         final Unit motorUnit = UnitGroup.UNITS_MOTOR_DIMENSIONS.getDefaultUnit();
378                                         motorTable.addCell(ITextHelper.createCell(motorUnit.toString(motor.getDiameter()) +
379                                                                                                                                 "/" +
380                                                                                                                                 motorUnit.toString(motor.getLength()) + " " +
381                                                                                                                                 motorUnit.toString(), border));
382                                         
383                                         // Sum up total count
384                                         totalMotorCount += motorCount;
385                                         totalPropMass += propMass * motorCount;
386                                         totalImpulse += motor.getTotalImpulseEstimate() * motorCount;
387                                         totalTTW += ttw * motorCount;
388                                 }
389                         }
390                 }
391                 
392                 if (totalMotorCount > 1) {
393                         int border = Rectangle.TOP;
394                         final PdfPCell motorVCell = ITextHelper.createCell("Total:", border);
395                         motorVCell.setPaddingLeft(mPad);
396                         motorTable.addCell(motorVCell);
397                         motorTable.addCell(ITextHelper.createCell("", border));
398                         motorTable.addCell(ITextHelper.createCell("", border));
399                         motorTable.addCell(ITextHelper.createCell("", border));
400                         motorTable.addCell(ITextHelper.createCell(
401                                                 UnitGroup.UNITS_IMPULSE.getDefaultUnit().toStringUnit(totalImpulse), border));
402                         motorTable.addCell(ITextHelper.createCell(
403                                         ttwFormat.format(totalTTW) + ":1", border));
404                         motorTable.addCell(ITextHelper.createCell(
405                                                 UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(totalPropMass), border));
406                         motorTable.addCell(ITextHelper.createCell("", border));
407                         
408                 }
409                 
410                 PdfPCell c = new PdfPCell(motorTable);
411                 c.setBorder(PdfPCell.LEFT);
412                 c.setBorderWidthTop(0f);
413                 parent.addCell(c);
414         }
415         
416         
417         /**
418          * Add the motor data for a motor configuration to the table.
419          *
420          * @param theRocket the rocket
421          * @param motorId   a motor configuration id
422          * @param parent    the parent to which the motor data will be added
423          * @param leading   the number of points for the leading
424          */
425         private void addFlightData(final Rocket theRocket, final String motorId, final PdfPTable parent, int leading) {
426                 
427                 // Perform flight simulation
428                 Rocket duplicate = theRocket.copyWithOriginalID();
429                 FlightData flight = null;
430                 try {
431                         Simulation simulation = ((SwingPreferences)Application.getPreferences()).getBackgroundSimulation(duplicate);
432                         simulation.getOptions().setMotorConfigurationID(motorId);
433                         simulation.simulate();
434                         flight = simulation.getSimulatedData();
435                 } catch (SimulationException e1) {
436                         // Ignore
437                 }
438                 
439                 // Output the flight data
440                 if (flight != null) {
441                         try {
442                                 final Unit distanceUnit = UnitGroup.UNITS_DISTANCE.getDefaultUnit();
443                                 final Unit velocityUnit = UnitGroup.UNITS_VELOCITY.getDefaultUnit();
444                                 final Unit flightTimeUnit = UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit();
445                                 
446                                 PdfPTable labelTable = new PdfPTable(2);
447                                 labelTable.setWidths(new int[] { 3, 2 });
448                                 final Paragraph chunk = ITextHelper.createParagraph(stripBrackets(
449                                                         theRocket.getMotorConfigurationNameOrDescription(motorId)), PrintUtilities.BOLD);
450                                 chunk.setLeading(leading);
451                                 chunk.setSpacingAfter(3f);
452                                 
453                                 document.add(chunk);
454                                 
455                                 final PdfPCell cell = ITextHelper.createCell(ALTITUDE, 2, 2);
456                                 cell.setUseBorderPadding(false);
457                                 cell.setBorderWidthTop(0f);
458                                 labelTable.addCell(cell);
459                                 labelTable.addCell(ITextHelper.createCell(distanceUnit.toStringUnit(flight.getMaxAltitude()), 2, 2));
460                                 
461                                 labelTable.addCell(ITextHelper.createCell(FLIGHT_TIME, 2, 2));
462                                 labelTable.addCell(ITextHelper.createCell(flightTimeUnit.toStringUnit(flight.getFlightTime()), 2, 2));
463                                 
464                                 labelTable.addCell(ITextHelper.createCell(TIME_TO_APOGEE, 2, 2));
465                                 labelTable.addCell(ITextHelper.createCell(flightTimeUnit.toStringUnit(flight.getTimeToApogee()), 2, 2));
466                                 
467                                 labelTable.addCell(ITextHelper.createCell(VELOCITY_OFF_PAD, 2, 2));
468                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getLaunchRodVelocity()), 2, 2));
469                                 
470                                 labelTable.addCell(ITextHelper.createCell(MAX_VELOCITY, 2, 2));
471                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getMaxVelocity()), 2, 2));
472                                 
473                                 labelTable.addCell(ITextHelper.createCell(DEPLOYMENT_VELOCITY, 2,2));
474                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getDeploymentVelocity()),2,2));
475                                 
476                                 labelTable.addCell(ITextHelper.createCell(LANDING_VELOCITY, 2, 2));
477                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getGroundHitVelocity()), 2, 2));
478                                 
479                                 //Add the table to the parent; have to wrap it in a cell
480                                 PdfPCell c = new PdfPCell(labelTable);
481                                 c.setBorder(PdfPCell.RIGHT);
482                                 c.setBorderWidthTop(0);
483                                 c.setTop(0);
484                                 parent.addCell(c);
485                         } catch (DocumentException e) {
486                                 log.error("Could not add flight data to document.", e);
487                         }
488                 }
489         }
490         
491         /**
492          * Strip [] brackets from a string.
493          *
494          * @param target the original string
495          *
496          * @return target with [] removed
497          */
498         private String stripBrackets(String target) {
499                 return stripLeftBracket(stripRightBracket(target));
500         }
501         
502         /**
503          * Strip [ from a string.
504          *
505          * @param target the original string
506          *
507          * @return target with [ removed
508          */
509         private String stripLeftBracket(String target) {
510                 return target.replace("[", "");
511         }
512         
513         /**
514          * Strip ] from a string.
515          *
516          * @param target the original string
517          *
518          * @return target with ] removed
519          */
520         private String stripRightBracket(String target) {
521                 return target.replace("]", "");
522         }
523         
524 }