Code

f8916655df152490daa179fbfc84cec78f520fbd
[inkscape.git] / src / extension / internal / pov-out.cpp
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 <extension/system.h>
30 #include <2geom/pathvector.h>
31 #include <2geom/rect.h>
32 #include <2geom/bezier-curve.h>
33 #include <2geom/hvlinesegment.h>
34 #include "helper/geom.h"
35 #include "helper/geom-curves.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 {
51 //########################################################################
52 //# M E S S A G E S
53 //########################################################################
55 static void err(const char *fmt, ...)
56 {
57     va_list args;
58     g_log(NULL,  G_LOG_LEVEL_WARNING, "Pov-out err: ");
59     va_start(args, fmt);
60     g_logv(NULL, G_LOG_LEVEL_WARNING, fmt, args);
61     va_end(args);
62     g_log(NULL,  G_LOG_LEVEL_WARNING, "\n");
63 }
68 //########################################################################
69 //# U T I L I T Y
70 //########################################################################
74 static double
75 effective_opacity(SPItem const *item)
76 {
77     double ret = 1.0;
78     for (SPObject const *obj = item; obj; obj = obj->parent)
79         {
80         SPStyle const *const style = SP_OBJECT_STYLE(obj);
81         g_return_val_if_fail(style, ret);
82         ret *= SP_SCALE24_TO_FLOAT(style->opacity.value);
83         }
84     return ret;
85 }
91 //########################################################################
92 //# OUTPUT FORMATTING
93 //########################################################################
96 /**
97  * We want to control floating output format
98  */
99 static PovOutput::String dstr(double d)
101     char dbuf[G_ASCII_DTOSTR_BUF_SIZE+1];
102     g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE,
103                   "%.8f", (gdouble)d);
104     PovOutput::String s = dbuf;
105     return s;
108 #define DSTR(d) (dstr(d).c_str())
111 /**
112  *  Output data to the buffer, printf()-style
113  */
114 void PovOutput::out(const char *fmt, ...)
116     va_list args;
117     va_start(args, fmt);
118     gchar *output = g_strdup_vprintf(fmt, args);
119     va_end(args);
120     outbuf.append(output);
121     g_free(output);
128 /**
129  *  Output a 2d vector
130  */
131 void PovOutput::vec2(double a, double b)
133     out("<%s, %s>", DSTR(a), DSTR(b));
138 /**
139  * Output a 3d vector
140  */
141 void PovOutput::vec3(double a, double b, double c)
143     out("<%s, %s, %s>", DSTR(a), DSTR(b), DSTR(c));
148 /**
149  *  Output a v4d ector
150  */
151 void PovOutput::vec4(double a, double b, double c, double d)
153     out("<%s, %s, %s, %s>", DSTR(a), DSTR(b), DSTR(c), DSTR(d));
158 /**
159  *  Output an rgbf color vector
160  */
161 void PovOutput::rgbf(double r, double g, double b, double f)
163     //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
164     out("rgbf ");
165     vec4(r, g, b, f);
170 /**
171  *  Output one bezier's start, start-control, end-control, and end nodes
172  */
173 void PovOutput::segment(int segNr,
174                         double startX,     double startY,
175                         double startCtrlX, double startCtrlY,
176                         double endCtrlX,   double endCtrlY,
177                         double endX,       double endY)
179     //"    /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
180     out("    /*%4d*/ ", segNr);
181     vec2(startX,     startY);
182     out(", ");
183     vec2(startCtrlX, startCtrlY);
184     out(", ");
185     vec2(endCtrlX,   endCtrlY);
186     out(", ");
187     vec2(endX,       endY);
194 /**
195  * Output the file header
196  */
197 bool PovOutput::doHeader()
199     time_t tim = time(NULL);
200     out("/*###################################################################\n");
201     out("### This PovRay document was generated by Inkscape\n");
202     out("### http://www.inkscape.org\n");
203     out("### Created: %s",   ctime(&tim));
204     out("### Version: %s\n", Inkscape::version_string);
205     out("#####################################################################\n");
206     out("### NOTES:\n");
207     out("### ============\n");
208     out("### POVRay information can be found at\n");
209     out("### http://www.povray.org\n");
210     out("###\n");
211     out("### The 'AllShapes' objects at the bottom are provided as a\n");
212     out("### preview of how the output would look in a trace.  However,\n");
213     out("### the main intent of this file is to provide the individual\n");
214     out("### shapes for inclusion in a POV project.\n");
215     out("###\n");
216     out("### For an example of how to use this file, look at\n");
217     out("### share/examples/istest.pov\n");
218     out("###\n");
219     out("### If you have any problems with this output, please see the\n");
220     out("### Inkscape project at http://www.inkscape.org, or visit\n");
221     out("### the #inkscape channel on irc.freenode.net . \n");
222     out("###\n");
223     out("###################################################################*/\n");
224     out("\n\n");
225     out("/*###################################################################\n");
226     out("##   Exports in this file\n");
227     out("##==========================\n");
228     out("##    Shapes   : %d\n", nrShapes);
229     out("##    Segments : %d\n", nrSegments);
230     out("##    Nodes    : %d\n", nrNodes);
231     out("###################################################################*/\n");
232     out("\n\n\n");
233     return true;
238 /**
239  *  Output the file footer
240  */
241 bool PovOutput::doTail()
243     out("\n\n");
244     out("/*###################################################################\n");
245     out("### E N D    F I L E\n");
246     out("###################################################################*/\n");
247     out("\n\n");
248     return true;
253 /**
254  *  Output the curve data to buffer
255  */
256 bool PovOutput::doCurve(SPItem *item, const String &id)
258     using Geom::X;
259     using Geom::Y;
261     //### Get the Shape
262     if (!SP_IS_SHAPE(item))//Bulia's suggestion.  Allow all shapes
263         return true;
265     SPShape *shape = SP_SHAPE(item);
266     SPCurve *curve = shape->curve;
267     if (curve->is_empty())
268         return true;
270     nrShapes++;
272     PovShapeInfo shapeInfo;
273     shapeInfo.id    = id;
274     shapeInfo.color = "";
276     //Try to get the fill color of the shape
277     SPStyle *style = SP_OBJECT_STYLE(shape);
278     /* fixme: Handle other fill types, even if this means translating gradients to a single
279            flat colour. */
280     if (style)
281         {
282         if (style->fill.isColor())
283             {
284             // see color.h for how to parse SPColor
285             float rgb[3];
286             sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
287             double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
288                                       * effective_opacity(shape) );
289             //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
290             //                             rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
291             String rgbf = "rgbf <";
292             rgbf.append(dstr(rgb[0]));         rgbf.append(", ");
293             rgbf.append(dstr(rgb[1]));         rgbf.append(", ");
294             rgbf.append(dstr(rgb[2]));         rgbf.append(", ");
295             rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
296             shapeInfo.color += rgbf;
297             }
298         }
300     povShapes.push_back(shapeInfo); //passed all tests.  save the info
302     // convert the path to only lineto's and cubic curveto's:
303     Geom::Matrix tf = sp_item_i2d_affine(item);
304     Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curve->get_pathvector() * tf );
306     //Count the NR_CURVETOs/LINETOs (including closing line segment)
307     int segmentCount = 0;
308     for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it)
309         {
310         segmentCount += (*it).size();
312         // If segment not closed, add space for a closing segment.
313         if (!it->closed()) segmentCount += 1;
315         }
317     out("/*###################################################\n");
318     out("### PRISM:  %s\n", id.c_str());
319     out("###################################################*/\n");
320     out("#declare %s = prism {\n", id.c_str());
321     out("    linear_sweep\n");
322     out("    bezier_spline\n");
323     out("    1.0, //top\n");
324     out("    0.0, //bottom\n");
325     out("    %d //nr points\n", segmentCount * 4);
326     int segmentNr = 0;
328     nrSegments += segmentCount;
330     /**
331      *   at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
332      */     
333     Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() ); 
334    
335    
336     /**
337      * For all Subpaths in the <path>
338      */      
339     for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit)
340         {
342         cminmax.expandTo(pit->initialPoint());
344         /**
345          * For all segments in the subpath, including extra closing segment defined by 2geom
346          */                      
347         for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit)
348             {
350             // If path is closed, we don't need extra closing segment.
351             if( pit->closed() && cit == pit->end() )
352                 continue;
354             if( is_straight_curve(*cit) )
355                 {
356                 Geom::Point p0 = cit->initialPoint();
357                 Geom::Point p1 = cit->finalPoint();
358                 segment(segmentNr++,
359                         p0[X], p0[Y], p0[X], p0[Y], p1[X], p1[Y], p1[X], p1[Y] );
360                 nrNodes += 8;
361                 }
362             else if(Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const*>(&*cit))
363                             {
364                 std::vector<Geom::Point> points = cubic->points();
365                 Geom::Point p0 = points[0];
366                 Geom::Point p1 = points[1];
367                 Geom::Point p2 = points[2];
368                 Geom::Point p3 = points[3];
369                 segment(segmentNr++,
370                             p0[X],p0[Y], p1[X],p1[Y], p2[X],p2[Y], p3[X],p3[Y]);
371                 nrNodes += 8;
372                 }
373             else
374                             {
375                 err("logical error, because pathv_to_linear_and_cubic_beziers was used");
376                 return false;
377                 }
379             if (segmentNr < segmentCount)
380                 out(",\n");
381             else
382                 out("\n");
383             if (segmentNr > segmentCount)
384                 {
385                 err("Too many segments");
386                 return false;
387                 }
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));
402     out("#declare %s_CENTER_X = %s;\n", id.c_str(), DSTR((cmaxx+cminx)/2.0));
403     out("#declare %s_MAX_X    = %s;\n", id.c_str(), DSTR(cmaxx));
404     out("#declare %s_WIDTH    = %s;\n", id.c_str(), DSTR(cmaxx-cminx));
405     out("#declare %s_MIN_Y    = %s;\n", id.c_str(), DSTR(cminy));
406     out("#declare %s_CENTER_Y = %s;\n", id.c_str(), DSTR((cmaxy+cminy)/2.0));
407     out("#declare %s_MAX_Y    = %s;\n", id.c_str(), DSTR(cmaxy));
408     out("#declare %s_HEIGHT   = %s;\n", id.c_str(), DSTR(cmaxy-cminy));
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;
428 /**
429  *  Descend the svg tree recursively, translating data
430  */
431 bool PovOutput::doTreeRecursive(SPDocument *doc, SPObject *obj)
434     String id;
435     if (!obj->id)
436         {
437         char buf[16];
438         sprintf(buf, "id%d", idIndex++);
439         id = buf;
440         }
441     else
442         {
443         id = obj->id;
444         }
446     if (SP_IS_ITEM(obj))
447         {
448         SPItem *item = SP_ITEM(obj);
449         if (!doCurve(item, id))
450             return false;
451         }
453     /**
454      * Descend into children
455      */
456     for (SPObject *child = obj->firstChild() ; child ; child = child->next)
457         {
458                 if (!doTreeRecursive(doc, child))
459                     return false;
460                 }
462     return true;
465 /**
466  *  Output the curve data to buffer
467  */
468 bool PovOutput::doTree(SPDocument *doc)
470     double bignum = 1000000.0;
471     minx  =  bignum;
472     maxx  = -bignum;
473     miny  =  bignum;
474     maxy  = -bignum;
476     if (!doTreeRecursive(doc, doc->root))
477         return false;
479     //## Let's make a union of all of the Shapes
480     if (povShapes.size()>0)
481         {
482         String id = "AllShapes";
483         char *pfx = (char *)id.c_str();
484         out("/*###################################################\n");
485         out("### UNION OF ALL SHAPES IN DOCUMENT\n");
486         out("###################################################*/\n");
487         out("\n\n");
488         out("/**\n");
489         out(" * Allow the user to redefine the finish{}\n");
490         out(" * by declaring it before #including this file\n");
491         out(" */\n");
492         out("#ifndef (%s_Finish)\n", pfx);
493         out("#declare %s_Finish = finish {\n", pfx);
494         out("    phong 0.5\n");
495         out("    reflection 0.3\n");
496         out("    specular 0.5\n");
497         out("}\n");
498         out("#end\n");
499         out("\n\n");
500         out("#declare %s = union {\n", id.c_str());
501         for (unsigned i = 0 ; i < povShapes.size() ; i++)
502             {
503             out("    object { %s\n", povShapes[i].id.c_str());
504             out("        texture { \n");
505             if (povShapes[i].color.length()>0)
506                 out("            pigment { %s }\n", povShapes[i].color.c_str());
507             else
508                 out("            pigment { rgb <0,0,0> }\n");
509             out("            finish { %s_Finish }\n", pfx);
510             out("            } \n");
511             out("        } \n");
512             }
513         out("}\n\n\n\n");
516         double zinc   = 0.2 / (double)povShapes.size();
517         out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
518         out("\n\n");
519         out("/**\n");
520         out(" * Allow the user to redefine the Z-Increment\n");
521         out(" */\n");
522         out("#ifndef (AllShapes_Z_Increment)\n");
523         out("#declare AllShapes_Z_Increment = %s;\n", DSTR(zinc));
524         out("#end\n");
525         out("\n");
526         out("#declare AllShapes_Z_Scale = 1.0;\n");
527         out("\n\n");
528         out("#declare %s_Z = union {\n", pfx);
530         for (unsigned i = 0 ; i < povShapes.size() ; i++)
531             {
532             out("    object { %s\n", povShapes[i].id.c_str());
533             out("        texture { \n");
534             if (povShapes[i].color.length()>0)
535                 out("            pigment { %s }\n", povShapes[i].color.c_str());
536             else
537                 out("            pigment { rgb <0,0,0> }\n");
538             out("            finish { %s_Finish }\n", pfx);
539             out("            } \n");
540             out("        scale <1, %s_Z_Scale, 1>\n", pfx);
541             out("        } \n");
542             out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
543                     pfx, pfx, pfx);
544             }
546         out("}\n");
548         out("#declare %s_MIN_X    = %s;\n", pfx, DSTR(minx));
549         out("#declare %s_CENTER_X = %s;\n", pfx, DSTR((maxx+minx)/2.0));
550         out("#declare %s_MAX_X    = %s;\n", pfx, DSTR(maxx));
551         out("#declare %s_WIDTH    = %s;\n", pfx, DSTR(maxx-minx));
552         out("#declare %s_MIN_Y    = %s;\n", pfx, DSTR(miny));
553         out("#declare %s_CENTER_Y = %s;\n", pfx, DSTR((maxy+miny)/2.0));
554         out("#declare %s_MAX_Y    = %s;\n", pfx, DSTR(maxy));
555         out("#declare %s_HEIGHT   = %s;\n", pfx, DSTR(maxy-miny));
556         out("/*##############################################\n");
557         out("### end %s\n", id.c_str());
558         out("##############################################*/\n");
559         out("\n\n");
560         }
562     return true;
566 //########################################################################
567 //# M A I N    O U T P U T
568 //########################################################################
572 /**
573  *  Set values back to initial state
574  */
575 void PovOutput::reset()
577     nrNodes    = 0;
578     nrSegments = 0;
579     nrShapes   = 0;
580     idIndex    = 0;
581     outbuf.clear();
582     povShapes.clear();
587 /**
588  * Saves the Shapes of an Inkscape SVG file as PovRay spline definitions
589  */
590 void PovOutput::saveDocument(SPDocument *doc, gchar const *filename_utf8)
592     reset();
594     //###### SAVE IN POV FORMAT TO BUFFER
595     //# Lets do the curves first, to get the stats
596     if (!doTree(doc))
597         {
598         err("Could not output curves for %s", filename_utf8);
599         return;
600         }
601         
602     String curveBuf = outbuf;
603     outbuf.clear();
605     if (!doHeader())
606         {
607         err("Could not write header for %s", filename_utf8);
608         return;
609         }
611     outbuf.append(curveBuf);
613     if (!doTail())
614         {
615         err("Could not write footer for %s", filename_utf8);
616         return;
617         }
622     //###### WRITE TO FILE
623     Inkscape::IO::dump_fopen_call(filename_utf8, "L");
624     FILE *f = Inkscape::IO::fopen_utf8name(filename_utf8, "w");
625     if (!f)
626         return;
628     for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
629         {
630         int ch = *iter;
631         fputc(ch, f);
632         }
634     fclose(f);
640 //########################################################################
641 //# EXTENSION API
642 //########################################################################
646 #include "clear-n_.h"
650 /**
651  * API call to save document
652 */
653 void
654 PovOutput::save(Inkscape::Extension::Output */*mod*/,
655                         SPDocument *doc, gchar const *filename_utf8)
657     /* See comments in JavaFSOutput::save re the name `filename_utf8'. */
658     saveDocument(doc, filename_utf8);
663 /**
664  * Make sure that we are in the database
665  */
666 bool PovOutput::check (Inkscape::Extension::Extension */*module*/)
668     /* We don't need a Key
669     if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
670         return FALSE;
671     */
673     return true;
678 /**
679  * This is the definition of PovRay output.  This function just
680  * calls the extension system with the memory allocated XML that
681  * describes the data.
682 */
683 void
684 PovOutput::init()
686     Inkscape::Extension::build_from_mem(
687         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
688             "<name>" N_("PovRay Output") "</name>\n"
689             "<id>org.inkscape.output.pov</id>\n"
690             "<output>\n"
691                 "<extension>.pov</extension>\n"
692                 "<mimetype>text/x-povray-script</mimetype>\n"
693                 "<filetypename>" N_("PovRay (*.pov) (paths and shapes only)") "</filetypename>\n"
694                 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
695             "</output>\n"
696         "</inkscape-extension>",
697         new PovOutput());
704 }  // namespace Internal
705 }  // namespace Extension
706 }  // namespace Inkscape
709 /*
710   Local Variables:
711   mode:c++
712   c-file-style:"stroustrup"
713   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
714   indent-tabs-mode:nil
715   fill-column:99
716   End:
717 */
718 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :