Code

remove many needless references to n-art-bpath.h
[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 <io/sys.h>
37 #include <string>
38 #include <stdio.h>
39 #include <stdarg.h>
42 namespace Inkscape
43 {
44 namespace Extension
45 {
46 namespace Internal
47 {
52 //########################################################################
53 //# U T I L I T Y
54 //########################################################################
58 /**
59  * This function searches the Repr tree recursively from the given node,
60  * and adds refs to all nodes with the given name, to the result vector
61  */
62 static void
63 findElementsByTagName(std::vector<Inkscape::XML::Node *> &results,
64                       Inkscape::XML::Node *node,
65                       char const *name)
66 {
67     if ( !name || strcmp(node->name(), name) == 0 )
68         results.push_back(node);
70     for (Inkscape::XML::Node *child = node->firstChild() ; child ;
71               child = child->next())
72         findElementsByTagName( results, child, name );
74 }
80 static double
81 effective_opacity(SPItem const *item)
82 {
83     double ret = 1.0;
84     for (SPObject const *obj = item; obj; obj = obj->parent)
85         {
86         SPStyle const *const style = SP_OBJECT_STYLE(obj);
87         g_return_val_if_fail(style, ret);
88         ret *= SP_SCALE24_TO_FLOAT(style->opacity.value);
89         }
90     return ret;
91 }
97 //########################################################################
98 //# OUTPUT FORMATTING
99 //########################################################################
102 /**
103  * We want to control floating output format
104  */
105 static PovOutput::String dstr(double d)
107     char dbuf[G_ASCII_DTOSTR_BUF_SIZE+1];
108     g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE,
109                   "%.8f", (gdouble)d);
110     PovOutput::String s = dbuf;
111     return s;
117 /**
118  *  Output data to the buffer, printf()-style
119  */
120 void PovOutput::out(const char *fmt, ...)
122     va_list args;
123     va_start(args, fmt);
124     gchar *output = g_strdup_vprintf(fmt, args);
125     va_end(args);
126     outbuf.append(output);
127     g_free(output);
134 /**
135  *  Output a 2d vector
136  */
137 void PovOutput::vec2(double a, double b)
139     out("<%s, %s>", dstr(a).c_str(), dstr(b).c_str());
144 /**
145  * Output a 3d vector
146  */
147 void PovOutput::vec3(double a, double b, double c)
149     out("<%s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(), dstr(c).c_str());
154 /**
155  *  Output a v4d ector
156  */
157 void PovOutput::vec4(double a, double b, double c, double d)
159     out("<%s, %s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(),
160                  dstr(c).c_str(), dstr(d).c_str());
165 /**
166  *  Output an rgbf color vector
167  */
168 void PovOutput::rgbf(double r, double g, double b, double f)
170     //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
171     out("rgbf ");
172     vec4(r, g, b, f);
177 /**
178  *  Output one bezier's start, start-control, end-control, and end nodes
179  */
180 void PovOutput::segment(int segNr,
181                         double startX,     double startY,
182                         double startCtrlX, double startCtrlY,
183                         double endCtrlX,   double endCtrlY,
184                         double endX,       double endY)
186     //"    /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
187     out("    /*%4d*/ ", segNr);
188     vec2(startX,     startY);
189     out(", ");
190     vec2(startCtrlX, startCtrlY);
191     out(", ");
192     vec2(endCtrlX,   endCtrlY);
193     out(", ");
194     vec2(endX,       endY);
201 /**
202  * Output the file header
203  */
204 bool PovOutput::doHeader()
206     time_t tim = time(NULL);
207     out("/*###################################################################\n");
208     out("### This PovRay document was generated by Inkscape\n");
209     out("### http://www.inkscape.org\n");
210     out("### Created: %s", ctime(&tim));
211     out("### Version: %s\n", INKSCAPE_VERSION);
212     out("#####################################################################\n");
213     out("### NOTES:\n");
214     out("### ============\n");
215     out("### POVRay information can be found at\n");
216     out("### http://www.povray.org\n");
217     out("###\n");
218     out("### The 'AllShapes' objects at the bottom are provided as a\n");
219     out("### preview of how the output would look in a trace.  However,\n");
220     out("### the main intent of this file is to provide the individual\n");
221     out("### shapes for inclusion in a POV project.\n");
222     out("###\n");
223     out("### For an example of how to use this file, look at\n");
224     out("### share/examples/istest.pov\n");
225     out("###\n");
226     out("### If you have any problems with this output, please see the\n");
227     out("### Inkscape project at http://www.inkscape.org, or visit\n");
228     out("### the #inkscape channel on irc.freenode.net . \n");
229     out("###\n");
230     out("###################################################################*/\n");
231     out("\n\n");
232     out("/*###################################################################\n");
233     out("##   Exports in this file\n");
234     out("##==========================\n");
235     out("##    Shapes   : %d\n", nrShapes);
236     out("##    Segments : %d\n", nrSegments);
237     out("##    Nodes    : %d\n", nrNodes);
238     out("###################################################################*/\n");
239     out("\n\n\n");
240     return true;
245 /**
246  *  Output the file footer
247  */
248 bool PovOutput::doTail()
250     out("\n\n");
251     out("/*###################################################################\n");
252     out("### E N D    F I L E\n");
253     out("###################################################################*/\n");
254     out("\n\n");
255     return true;
260 /**
261  *  Output the curve data to buffer
262  */
263 bool PovOutput::doCurve(SPItem *item, const String &id)
265     using Geom::X;
266     using Geom::Y;
268     //### Get the Shape
269     if (!SP_IS_SHAPE(item))//Bulia's suggestion.  Allow all shapes
270         return true;
272     SPShape *shape = SP_SHAPE(item);
273     SPCurve *curve = shape->curve;
274     if (curve->is_empty())
275         return true;
277     nrShapes++;
279     PovShapeInfo shapeInfo;
280     shapeInfo.id    = id;
281     shapeInfo.color = "";
283     //Try to get the fill color of the shape
284     SPStyle *style = SP_OBJECT_STYLE(shape);
285     /* fixme: Handle other fill types, even if this means translating gradients to a single
286            flat colour. */
287     if (style)
288         {
289         if (style->fill.isColor())
290             {
291             // see color.h for how to parse SPColor
292             float rgb[3];
293             sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
294             double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
295                                       * effective_opacity(shape) );
296             //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
297             //                             rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
298             String rgbf = "rgbf <";
299             rgbf.append(dstr(rgb[0]));         rgbf.append(", ");
300             rgbf.append(dstr(rgb[1]));         rgbf.append(", ");
301             rgbf.append(dstr(rgb[2]));         rgbf.append(", ");
302             rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
303             shapeInfo.color += rgbf;
304             }
305         }
307     povShapes.push_back(shapeInfo); //passed all tests.  save the info
309     // convert the path to only lineto's and cubic curveto's:
310     Geom::Matrix tf = sp_item_i2d_affine(item);
311     Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curve->get_pathvector() * tf );
313     //Count the NR_CURVETOs/LINETOs (including closing line segment)
314     int segmentCount = 0;
315     for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it)
316             {
317         segmentCount += (*it).size();
318         if (it->closed())
319             segmentCount += 1;
320         }
322     out("/*###################################################\n");
323     out("### PRISM:  %s\n", id.c_str());
324     out("###################################################*/\n");
325     out("#declare %s = prism {\n", id.c_str());
326     out("    linear_sweep\n");
327     out("    bezier_spline\n");
328     out("    1.0, //top\n");
329     out("    0.0, //bottom\n");
330     out("    %d //nr points\n", segmentCount * 4);
331     int segmentNr = 0;
333     nrSegments += segmentCount;
335     /**
336      *   at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
337      */     
338     Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() ); 
339    
340    
341     /**
342      * For all Subpaths in the <path>
343      */      
344     for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit)
345         {
347         cminmax.expandTo(pit->initialPoint());
349         /**
350          * For all segments in the subpath
351          */                      
352         for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit)
353                     {
355             if( dynamic_cast<Geom::LineSegment const *> (&*cit) ||
356                     dynamic_cast<Geom::HLineSegment const *>(&*cit) ||
357                     dynamic_cast<Geom::VLineSegment const *>(&*cit) )
358                 {
359                 Geom::Point p0 = cit->initialPoint();
360                 Geom::Point p1 = cit->finalPoint();
361                 segment(segmentNr++,
362                         p0[X], p0[Y], p0[X], p0[Y], p1[X], p1[Y], p1[X], p1[Y] );
363                 nrNodes += 8;
364                 }
365             else if(Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const*>(&*cit))
366                             {
367                 std::vector<Geom::Point> points = cubic->points();
368                 Geom::Point p0 = points[0];
369                 Geom::Point p1 = points[1];
370                 Geom::Point p2 = points[2];
371                 Geom::Point p3 = points[3];
372                 segment(segmentNr++,
373                             p0[X],p0[Y], p1[X],p1[Y], p2[X],p2[Y], p3[X],p3[Y]);
374                 nrNodes += 8;
375                 }
376             else
377                             {
378                 g_warning("logical error, because pathv_to_linear_and_cubic_beziers was used");
379                 return false;
380                 }
382             if (segmentNr < segmentCount)
383                 out(",\n");
384             else
385                 out("\n");
387             cminmax.expandTo(cit->finalPoint());
389             }
390         }
392     out("}\n");
394     double cminx = cminmax.min()[X];
395     double cmaxx = cminmax.max()[X];
396     double cminy = cminmax.min()[Y];
397     double cmaxy = cminmax.max()[Y];
399     out("#declare %s_MIN_X    = %s;\n", id.c_str(), dstr(cminx).c_str());
400     out("#declare %s_CENTER_X = %s;\n", id.c_str(), dstr((cmaxx+cminx)/2.0).c_str());
401     out("#declare %s_MAX_X    = %s;\n", id.c_str(), dstr(cmaxx).c_str());
402     out("#declare %s_WIDTH    = %s;\n", id.c_str(), dstr(cmaxx-cminx).c_str());
403     out("#declare %s_MIN_Y    = %s;\n", id.c_str(), dstr(cminy).c_str());
404     out("#declare %s_CENTER_Y = %s;\n", id.c_str(), dstr((cmaxy+cminy)/2.0).c_str());
405     out("#declare %s_MAX_Y    = %s;\n", id.c_str(), dstr(cmaxy).c_str());
406     out("#declare %s_HEIGHT   = %s;\n", id.c_str(), dstr(cmaxy-cminy).c_str());
407     if (shapeInfo.color.length()>0)
408         out("#declare %s_COLOR    = %s;\n",
409                 id.c_str(), shapeInfo.color.c_str());
410     out("/*###################################################\n");
411     out("### end %s\n", id.c_str());
412     out("###################################################*/\n\n\n\n");
414     if (cminx < minx)
415         minx = cminx;
416     if (cmaxx > maxx)
417         maxx = cmaxx;
418     if (cminy < miny)
419         miny = cminy;
420     if (cmaxy > maxy)
421         maxy = cmaxy;
423     return true;
426 /**
427  *  Output the curve data to buffer
428  */
429 bool PovOutput::doCurvesRecursive(SPDocument *doc, Inkscape::XML::Node *node)
431     /**
432      * If the object is an Item, try processing it
433      */      
434     char *str  = (char *) node->attribute("id");
435     SPObject *reprobj = doc->getObjectByRepr(node);
436     if (SP_IS_ITEM(reprobj) && str)
437         {
438         SPItem *item = SP_ITEM(reprobj);
439         String id = str;
440         if (!doCurve(item, id))
441             return false;
442         }
444     /**
445      * Descend into children
446      */      
447     for (Inkscape::XML::Node *child = node->firstChild() ; child ;
448               child = child->next())
449         {
450                 if (!doCurvesRecursive(doc, child))
451                     return false;
452                 }
454     return true;
457 /**
458  *  Output the curve data to buffer
459  */
460 bool PovOutput::doCurves(SPDocument *doc)
462     double bignum = 1000000.0;
463     minx  =  bignum;
464     maxx  = -bignum;
465     miny  =  bignum;
466     maxy  = -bignum;
468     if (!doCurvesRecursive(doc, doc->rroot))
469         return false;
471     //## Let's make a union of all of the Shapes
472     if (povShapes.size()>0)
473         {
474         String id = "AllShapes";
475         char *pfx = (char *)id.c_str();
476         out("/*###################################################\n");
477         out("### UNION OF ALL SHAPES IN DOCUMENT\n");
478         out("###################################################*/\n");
479         out("\n\n");
480         out("/**\n");
481         out(" * Allow the user to redefine the finish{}\n");
482         out(" * by declaring it before #including this file\n");
483         out(" */\n");
484         out("#ifndef (%s_Finish)\n", pfx);
485         out("#declare %s_Finish = finish {\n", pfx);
486         out("    phong 0.5\n");
487         out("    reflection 0.3\n");
488         out("    specular 0.5\n");
489         out("}\n");
490         out("#end\n");
491         out("\n\n");
492         out("#declare %s = union {\n", id.c_str());
493         for (unsigned i = 0 ; i < povShapes.size() ; i++)
494             {
495             out("    object { %s\n", povShapes[i].id.c_str());
496             out("        texture { \n");
497             if (povShapes[i].color.length()>0)
498                 out("            pigment { %s }\n", povShapes[i].color.c_str());
499             else
500                 out("            pigment { rgb <0,0,0> }\n");
501             out("            finish { %s_Finish }\n", pfx);
502             out("            } \n");
503             out("        } \n");
504             }
505         out("}\n\n\n\n");
508         double zinc   = 0.2 / (double)povShapes.size();
509         out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
510         out("\n\n");
511         out("/**\n");
512         out(" * Allow the user to redefine the Z-Increment\n");
513         out(" */\n");
514         out("#ifndef (AllShapes_Z_Increment)\n");
515         out("#declare AllShapes_Z_Increment = %s;\n", dstr(zinc).c_str());
516         out("#end\n");
517         out("\n");
518         out("#declare AllShapes_Z_Scale = 1.0;\n");
519         out("\n\n");
520         out("#declare %s_Z = union {\n", pfx);
522         for (unsigned i = 0 ; i < povShapes.size() ; i++)
523             {
524             out("    object { %s\n", povShapes[i].id.c_str());
525             out("        texture { \n");
526             if (povShapes[i].color.length()>0)
527                 out("            pigment { %s }\n", povShapes[i].color.c_str());
528             else
529                 out("            pigment { rgb <0,0,0> }\n");
530             out("            finish { %s_Finish }\n", pfx);
531             out("            } \n");
532             out("        scale <1, %s_Z_Scale, 1>\n", pfx);
533             out("        } \n");
534             out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
535                     pfx, pfx, pfx);
536             }
538         out("}\n");
540         out("#declare %s_MIN_X    = %s;\n", pfx, dstr(minx).c_str());
541         out("#declare %s_CENTER_X = %s;\n", pfx, dstr((maxx+minx)/2.0).c_str());
542         out("#declare %s_MAX_X    = %s;\n", pfx, dstr(maxx).c_str());
543         out("#declare %s_WIDTH    = %s;\n", pfx, dstr(maxx-minx).c_str());
544         out("#declare %s_MIN_Y    = %s;\n", pfx, dstr(miny).c_str());
545         out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((maxy+miny)/2.0).c_str());
546         out("#declare %s_MAX_Y    = %s;\n", pfx, dstr(maxy).c_str());
547         out("#declare %s_HEIGHT   = %s;\n", pfx, dstr(maxy-miny).c_str());
548         out("/*##############################################\n");
549         out("### end %s\n", id.c_str());
550         out("##############################################*/\n");
551         out("\n\n");
552         }
554     return true;
558 //########################################################################
559 //# M A I N    O U T P U T
560 //########################################################################
564 /**
565  *  Set values back to initial state
566  */
567 void PovOutput::reset()
569     nrNodes    = 0;
570     nrSegments = 0;
571     nrShapes   = 0;
572     outbuf.clear();
573     povShapes.clear();
578 /**
579  * Saves the Shapes of an Inkscape SVG file as PovRay spline definitions
580  */
581 void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
583     reset();
585     //###### SAVE IN POV FORMAT TO BUFFER
586     //# Lets do the curves first, to get the stats
587     if (!doCurves(doc))
588         {
589         g_warning("Could not output curves for %s\n", uri);
590         return;
591         }
592         
593     String curveBuf = outbuf;
594     outbuf.clear();
596     if (!doHeader())
597         {
598         g_warning("Could not write header for %s\n", uri);
599         return;
600         }
602     outbuf.append(curveBuf);
604     if (!doTail())
605         {
606         g_warning("Could not write footer for %s\n", uri);
607         return;
608         }
613     //###### WRITE TO FILE
614     Inkscape::IO::dump_fopen_call(uri, "L");
615     FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
616     if (!f)
617         return;
619     for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
620         {
621         int ch = *iter;
622         fputc(ch, f);
623         }
625     fclose(f);
631 //########################################################################
632 //# EXTENSION API
633 //########################################################################
637 #include "clear-n_.h"
641 /**
642  * API call to save document
643 */
644 void
645 PovOutput::save(Inkscape::Extension::Output *mod,
646                         SPDocument *doc, gchar const *uri)
648     saveDocument(doc, uri);
653 /**
654  * Make sure that we are in the database
655  */
656 bool PovOutput::check (Inkscape::Extension::Extension *module)
658     /* We don't need a Key
659     if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
660         return FALSE;
661     */
663     return true;
668 /**
669  * This is the definition of PovRay output.  This function just
670  * calls the extension system with the memory allocated XML that
671  * describes the data.
672 */
673 void
674 PovOutput::init()
676     Inkscape::Extension::build_from_mem(
677         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
678             "<name>" N_("PovRay Output") "</name>\n"
679             "<id>org.inkscape.output.pov</id>\n"
680             "<output>\n"
681                 "<extension>.pov</extension>\n"
682                 "<mimetype>text/x-povray-script</mimetype>\n"
683                 "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
684                 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
685             "</output>\n"
686         "</inkscape-extension>",
687         new PovOutput());
694 }  // namespace Internal
695 }  // namespace Extension
696 }  // namespace Inkscape
699 /*
700   Local Variables:
701   mode:c++
702   c-file-style:"stroustrup"
703   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
704   indent-tabs-mode:nil
705   fill-column:99
706   End:
707 */
708 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :