1 /*
2 * A simple utility for exporting Inkscape svg Shapes as PovRay bezier
3 * prisms. Note that this is output-only, and would thus seem to be
4 * better placed as an 'export' rather than 'output'. However, Export
5 * handles all or partial documents, while this outputs ALL shapes in
6 * the current SVG document.
7 *
8 * For information on the PovRay file format, see:
9 * http://www.povray.org
10 *
11 * Authors:
12 * Bob Jamison <ishmal@inkscape.org>
13 *
14 * Copyright (C) 2004-2008 Authors
15 *
16 * Released under GNU GPL, read the file 'COPYING' for more information
17 */
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23 #include "pov-out.h"
24 #include <inkscape.h>
25 #include <inkscape_version.h>
26 #include <sp-path.h>
27 #include <style.h>
28 #include <display/curve.h>
29 #include <libnr/n-art-bpath.h>
30 #include <extension/system.h>
31 #include <2geom/pathvector.h>
32 #include <2geom/rect.h>
33 #include <2geom/bezier-curve.h>
34 #include <2geom/hvlinesegment.h>
35 #include "helper/geom.h"
36 #include <io/sys.h>
38 #include <string>
39 #include <stdio.h>
40 #include <stdarg.h>
43 namespace Inkscape
44 {
45 namespace Extension
46 {
47 namespace Internal
48 {
53 //########################################################################
54 //# U T I L I T Y
55 //########################################################################
59 /**
60 * This function searches the Repr tree recursively from the given node,
61 * and adds refs to all nodes with the given name, to the result vector
62 */
63 static void
64 findElementsByTagName(std::vector<Inkscape::XML::Node *> &results,
65 Inkscape::XML::Node *node,
66 char const *name)
67 {
68 if ( !name || strcmp(node->name(), name) == 0 )
69 results.push_back(node);
71 for (Inkscape::XML::Node *child = node->firstChild() ; child ;
72 child = child->next())
73 findElementsByTagName( results, child, name );
75 }
81 static double
82 effective_opacity(SPItem const *item)
83 {
84 double ret = 1.0;
85 for (SPObject const *obj = item; obj; obj = obj->parent)
86 {
87 SPStyle const *const style = SP_OBJECT_STYLE(obj);
88 g_return_val_if_fail(style, ret);
89 ret *= SP_SCALE24_TO_FLOAT(style->opacity.value);
90 }
91 return ret;
92 }
98 //########################################################################
99 //# OUTPUT FORMATTING
100 //########################################################################
103 /**
104 * We want to control floating output format
105 */
106 static PovOutput::String dstr(double d)
107 {
108 char dbuf[G_ASCII_DTOSTR_BUF_SIZE+1];
109 g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE,
110 "%.8f", (gdouble)d);
111 PovOutput::String s = dbuf;
112 return s;
113 }
118 /**
119 * Output data to the buffer, printf()-style
120 */
121 void PovOutput::out(const char *fmt, ...)
122 {
123 va_list args;
124 va_start(args, fmt);
125 gchar *output = g_strdup_vprintf(fmt, args);
126 va_end(args);
127 outbuf.append(output);
128 g_free(output);
129 }
135 /**
136 * Output a 2d vector
137 */
138 void PovOutput::vec2(double a, double b)
139 {
140 out("<%s, %s>", dstr(a).c_str(), dstr(b).c_str());
141 }
145 /**
146 * Output a 3d vector
147 */
148 void PovOutput::vec3(double a, double b, double c)
149 {
150 out("<%s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(), dstr(c).c_str());
151 }
155 /**
156 * Output a v4d ector
157 */
158 void PovOutput::vec4(double a, double b, double c, double d)
159 {
160 out("<%s, %s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(),
161 dstr(c).c_str(), dstr(d).c_str());
162 }
166 /**
167 * Output an rgbf color vector
168 */
169 void PovOutput::rgbf(double r, double g, double b, double f)
170 {
171 //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
172 out("rgbf ");
173 vec4(r, g, b, f);
174 }
178 /**
179 * Output one bezier's start, start-control, end-control, and end nodes
180 */
181 void PovOutput::segment(int segNr,
182 double startX, double startY,
183 double startCtrlX, double startCtrlY,
184 double endCtrlX, double endCtrlY,
185 double endX, double endY)
186 {
187 //" /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
188 out(" /*%4d*/ ", segNr);
189 vec2(startX, startY);
190 out(", ");
191 vec2(startCtrlX, startCtrlY);
192 out(", ");
193 vec2(endCtrlX, endCtrlY);
194 out(", ");
195 vec2(endX, endY);
196 }
202 /**
203 * Output the file header
204 */
205 bool PovOutput::doHeader()
206 {
207 time_t tim = time(NULL);
208 out("/*###################################################################\n");
209 out("### This PovRay document was generated by Inkscape\n");
210 out("### http://www.inkscape.org\n");
211 out("### Created: %s", ctime(&tim));
212 out("### Version: %s\n", INKSCAPE_VERSION);
213 out("#####################################################################\n");
214 out("### NOTES:\n");
215 out("### ============\n");
216 out("### POVRay information can be found at\n");
217 out("### http://www.povray.org\n");
218 out("###\n");
219 out("### The 'AllShapes' objects at the bottom are provided as a\n");
220 out("### preview of how the output would look in a trace. However,\n");
221 out("### the main intent of this file is to provide the individual\n");
222 out("### shapes for inclusion in a POV project.\n");
223 out("###\n");
224 out("### For an example of how to use this file, look at\n");
225 out("### share/examples/istest.pov\n");
226 out("###\n");
227 out("### If you have any problems with this output, please see the\n");
228 out("### Inkscape project at http://www.inkscape.org, or visit\n");
229 out("### the #inkscape channel on irc.freenode.net . \n");
230 out("###\n");
231 out("###################################################################*/\n");
232 out("\n\n");
233 out("/*###################################################################\n");
234 out("## Exports in this file\n");
235 out("##==========================\n");
236 out("## Shapes : %d\n", nrShapes);
237 out("## Segments : %d\n", nrSegments);
238 out("## Nodes : %d\n", nrNodes);
239 out("###################################################################*/\n");
240 out("\n\n\n");
241 return true;
242 }
246 /**
247 * Output the file footer
248 */
249 bool PovOutput::doTail()
250 {
251 out("\n\n");
252 out("/*###################################################################\n");
253 out("### E N D F I L E\n");
254 out("###################################################################*/\n");
255 out("\n\n");
256 return true;
257 }
261 /**
262 * Output the curve data to buffer
263 */
264 bool PovOutput::doCurve(SPItem *item, const String &id)
265 {
266 using Geom::X;
267 using Geom::Y;
269 Geom::Matrix tf = sp_item_i2d_affine(item);
271 //### Get the Shape
272 if (!SP_IS_SHAPE(item))//Bulia's suggestion. Allow all shapes
273 return true;
275 SPShape *shape = SP_SHAPE(item);
276 SPCurve *curve = shape->curve;
277 if (curve->is_empty())
278 return true;
280 nrShapes++;
282 PovShapeInfo shapeInfo;
283 shapeInfo.id = id;
284 shapeInfo.color = "";
286 //Try to get the fill color of the shape
287 SPStyle *style = SP_OBJECT_STYLE(shape);
288 /* fixme: Handle other fill types, even if this means translating gradients to a single
289 flat colour. */
290 if (style)
291 {
292 if (style->fill.isColor())
293 {
294 // see color.h for how to parse SPColor
295 float rgb[3];
296 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
297 double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
298 * effective_opacity(shape) );
299 //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
300 // rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
301 String rgbf = "rgbf <";
302 rgbf.append(dstr(rgb[0])); rgbf.append(", ");
303 rgbf.append(dstr(rgb[1])); rgbf.append(", ");
304 rgbf.append(dstr(rgb[2])); rgbf.append(", ");
305 rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
306 shapeInfo.color += rgbf;
307 }
308 }
310 povShapes.push_back(shapeInfo); //passed all tests. save the info
312 // convert the path to only lineto's and cubic curveto's:
313 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curve->get_pathvector() * tf );
315 //Count the NR_CURVETOs/LINETOs (including closing line segment)
316 int segmentCount = 0;
317 for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it)
318 {
319 segmentCount += (*it).size();
320 if (it->closed())
321 segmentCount += 1;
322 }
324 out("/*###################################################\n");
325 out("### PRISM: %s\n", id.c_str());
326 out("###################################################*/\n");
327 out("#declare %s = prism {\n", id.c_str());
328 out(" linear_sweep\n");
329 out(" bezier_spline\n");
330 out(" 1.0, //top\n");
331 out(" 0.0, //bottom\n");
332 out(" %d //nr points\n", segmentCount * 4);
333 int segmentNr = 0;
335 nrSegments += segmentCount;
337 /**
338 * at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
339 */
340 Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() );
343 /**
344 * For all Subpaths in the <path>
345 */
346 for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit)
347 {
349 cminmax.expandTo(pit->initialPoint());
351 /**
352 * For all segments in the subpath
353 */
354 for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit)
355 {
357 if( dynamic_cast<Geom::LineSegment const *> (&*cit) ||
358 dynamic_cast<Geom::HLineSegment const *>(&*cit) ||
359 dynamic_cast<Geom::VLineSegment const *>(&*cit) )
360 {
361 Geom::Point p0 = cit->initialPoint();
362 Geom::Point p1 = cit->finalPoint();
363 segment(segmentNr++,
364 p0[X], p0[Y], p0[X], p0[Y], p1[X], p1[Y], p1[X], p1[Y] );
365 nrNodes += 8;
366 }
367 else if(Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const*>(&*cit))
368 {
369 std::vector<Geom::Point> points = cubic->points();
370 Geom::Point p0 = points[0];
371 Geom::Point p1 = points[1];
372 Geom::Point p2 = points[2];
373 Geom::Point p3 = points[3];
374 segment(segmentNr++,
375 p0[X],p0[Y], p1[X],p1[Y], p2[X],p2[Y], p3[X],p3[Y]);
376 nrNodes += 8;
377 }
378 else
379 {
380 g_warning("logical error, because pathv_to_linear_and_cubic_beziers was used");
381 return false;
382 }
384 if (segmentNr < segmentCount)
385 out(",\n");
386 else
387 out("\n");
389 cminmax.expandTo(cit->finalPoint());
391 }
392 }
394 out("}\n");
396 double cminx = cminmax.min()[X];
397 double cmaxx = cminmax.max()[X];
398 double cminy = cminmax.min()[Y];
399 double cmaxy = cminmax.max()[Y];
401 out("#declare %s_MIN_X = %s;\n", id.c_str(), dstr(cminx).c_str());
402 out("#declare %s_CENTER_X = %s;\n", id.c_str(), dstr((cmaxx+cminx)/2.0).c_str());
403 out("#declare %s_MAX_X = %s;\n", id.c_str(), dstr(cmaxx).c_str());
404 out("#declare %s_WIDTH = %s;\n", id.c_str(), dstr(cmaxx-cminx).c_str());
405 out("#declare %s_MIN_Y = %s;\n", id.c_str(), dstr(cminy).c_str());
406 out("#declare %s_CENTER_Y = %s;\n", id.c_str(), dstr((cmaxy+cminy)/2.0).c_str());
407 out("#declare %s_MAX_Y = %s;\n", id.c_str(), dstr(cmaxy).c_str());
408 out("#declare %s_HEIGHT = %s;\n", id.c_str(), dstr(cmaxy-cminy).c_str());
409 if (shapeInfo.color.length()>0)
410 out("#declare %s_COLOR = %s;\n",
411 id.c_str(), shapeInfo.color.c_str());
412 out("/*###################################################\n");
413 out("### end %s\n", id.c_str());
414 out("###################################################*/\n\n\n\n");
416 if (cminx < minx)
417 minx = cminx;
418 if (cmaxx > maxx)
419 maxx = cmaxx;
420 if (cminy < miny)
421 miny = cminy;
422 if (cmaxy > maxy)
423 maxy = cmaxy;
425 return true;
426 }
428 /**
429 * Output the curve data to buffer
430 */
431 bool PovOutput::doCurvesRecursive(SPDocument *doc, Inkscape::XML::Node *node)
432 {
433 /**
434 * If the object is an Item, try processing it
435 */
436 char *str = (char *) node->attribute("id");
437 SPObject *reprobj = doc->getObjectByRepr(node);
438 if (SP_IS_ITEM(reprobj) && str)
439 {
440 SPItem *item = SP_ITEM(reprobj);
441 String id = str;
442 if (!doCurve(item, id))
443 return false;
444 }
446 /**
447 * Descend into children
448 */
449 for (Inkscape::XML::Node *child = node->firstChild() ; child ;
450 child = child->next())
451 {
452 if (!doCurvesRecursive(doc, child))
453 return false;
454 }
456 return true;
457 }
459 /**
460 * Output the curve data to buffer
461 */
462 bool PovOutput::doCurves(SPDocument *doc)
463 {
464 double bignum = 1000000.0;
465 minx = bignum;
466 maxx = -bignum;
467 miny = bignum;
468 maxy = -bignum;
470 if (!doCurvesRecursive(doc, doc->rroot))
471 return false;
473 //## Let's make a union of all of the Shapes
474 if (povShapes.size()>0)
475 {
476 String id = "AllShapes";
477 char *pfx = (char *)id.c_str();
478 out("/*###################################################\n");
479 out("### UNION OF ALL SHAPES IN DOCUMENT\n");
480 out("###################################################*/\n");
481 out("\n\n");
482 out("/**\n");
483 out(" * Allow the user to redefine the finish{}\n");
484 out(" * by declaring it before #including this file\n");
485 out(" */\n");
486 out("#ifndef (%s_Finish)\n", pfx);
487 out("#declare %s_Finish = finish {\n", pfx);
488 out(" phong 0.5\n");
489 out(" reflection 0.3\n");
490 out(" specular 0.5\n");
491 out("}\n");
492 out("#end\n");
493 out("\n\n");
494 out("#declare %s = union {\n", id.c_str());
495 for (unsigned i = 0 ; i < povShapes.size() ; i++)
496 {
497 out(" object { %s\n", povShapes[i].id.c_str());
498 out(" texture { \n");
499 if (povShapes[i].color.length()>0)
500 out(" pigment { %s }\n", povShapes[i].color.c_str());
501 else
502 out(" pigment { rgb <0,0,0> }\n");
503 out(" finish { %s_Finish }\n", pfx);
504 out(" } \n");
505 out(" } \n");
506 }
507 out("}\n\n\n\n");
510 double zinc = 0.2 / (double)povShapes.size();
511 out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
512 out("\n\n");
513 out("/**\n");
514 out(" * Allow the user to redefine the Z-Increment\n");
515 out(" */\n");
516 out("#ifndef (AllShapes_Z_Increment)\n");
517 out("#declare AllShapes_Z_Increment = %s;\n", dstr(zinc).c_str());
518 out("#end\n");
519 out("\n");
520 out("#declare AllShapes_Z_Scale = 1.0;\n");
521 out("\n\n");
522 out("#declare %s_Z = union {\n", pfx);
524 for (unsigned i = 0 ; i < povShapes.size() ; i++)
525 {
526 out(" object { %s\n", povShapes[i].id.c_str());
527 out(" texture { \n");
528 if (povShapes[i].color.length()>0)
529 out(" pigment { %s }\n", povShapes[i].color.c_str());
530 else
531 out(" pigment { rgb <0,0,0> }\n");
532 out(" finish { %s_Finish }\n", pfx);
533 out(" } \n");
534 out(" scale <1, %s_Z_Scale, 1>\n", pfx);
535 out(" } \n");
536 out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
537 pfx, pfx, pfx);
538 }
540 out("}\n");
542 out("#declare %s_MIN_X = %s;\n", pfx, dstr(minx).c_str());
543 out("#declare %s_CENTER_X = %s;\n", pfx, dstr((maxx+minx)/2.0).c_str());
544 out("#declare %s_MAX_X = %s;\n", pfx, dstr(maxx).c_str());
545 out("#declare %s_WIDTH = %s;\n", pfx, dstr(maxx-minx).c_str());
546 out("#declare %s_MIN_Y = %s;\n", pfx, dstr(miny).c_str());
547 out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((maxy+miny)/2.0).c_str());
548 out("#declare %s_MAX_Y = %s;\n", pfx, dstr(maxy).c_str());
549 out("#declare %s_HEIGHT = %s;\n", pfx, dstr(maxy-miny).c_str());
550 out("/*##############################################\n");
551 out("### end %s\n", id.c_str());
552 out("##############################################*/\n");
553 out("\n\n");
554 }
556 return true;
557 }
560 //########################################################################
561 //# M A I N O U T P U T
562 //########################################################################
566 /**
567 * Set values back to initial state
568 */
569 void PovOutput::reset()
570 {
571 nrNodes = 0;
572 nrSegments = 0;
573 nrShapes = 0;
574 outbuf.clear();
575 povShapes.clear();
576 }
580 /**
581 * Saves the Shapes of an Inkscape SVG file as PovRay spline definitions
582 */
583 void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
584 {
585 reset();
587 //###### SAVE IN POV FORMAT TO BUFFER
588 //# Lets do the curves first, to get the stats
589 if (!doCurves(doc))
590 {
591 g_warning("Could not output curves for %s\n", uri);
592 return;
593 }
595 String curveBuf = outbuf;
596 outbuf.clear();
598 if (!doHeader())
599 {
600 g_warning("Could not write header for %s\n", uri);
601 return;
602 }
604 outbuf.append(curveBuf);
606 if (!doTail())
607 {
608 g_warning("Could not write footer for %s\n", uri);
609 return;
610 }
615 //###### WRITE TO FILE
616 Inkscape::IO::dump_fopen_call(uri, "L");
617 FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
618 if (!f)
619 return;
621 for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
622 {
623 int ch = *iter;
624 fputc(ch, f);
625 }
627 fclose(f);
628 }
633 //########################################################################
634 //# EXTENSION API
635 //########################################################################
639 #include "clear-n_.h"
643 /**
644 * API call to save document
645 */
646 void
647 PovOutput::save(Inkscape::Extension::Output *mod,
648 SPDocument *doc, gchar const *uri)
649 {
650 saveDocument(doc, uri);
651 }
655 /**
656 * Make sure that we are in the database
657 */
658 bool PovOutput::check (Inkscape::Extension::Extension *module)
659 {
660 /* We don't need a Key
661 if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
662 return FALSE;
663 */
665 return true;
666 }
670 /**
671 * This is the definition of PovRay output. This function just
672 * calls the extension system with the memory allocated XML that
673 * describes the data.
674 */
675 void
676 PovOutput::init()
677 {
678 Inkscape::Extension::build_from_mem(
679 "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
680 "<name>" N_("PovRay Output") "</name>\n"
681 "<id>org.inkscape.output.pov</id>\n"
682 "<output>\n"
683 "<extension>.pov</extension>\n"
684 "<mimetype>text/x-povray-script</mimetype>\n"
685 "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
686 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
687 "</output>\n"
688 "</inkscape-extension>",
689 new PovOutput());
690 }
696 } // namespace Internal
697 } // namespace Extension
698 } // namespace Inkscape
701 /*
702 Local Variables:
703 mode:c++
704 c-file-style:"stroustrup"
705 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
706 indent-tabs-mode:nil
707 fill-column:99
708 End:
709 */
710 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :