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