Code

2ccbfd0f2a2d932c19f6f77f1e2e31d82079d832
[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 <libnr/n-art-bpath.h>
30 #include <extension/system.h>
31 #include <2geom/pathvector.h>
32 #include <2geom/rect.h>
33 #include "helper/geom.h"
34 #include <io/sys.h>
36 #include <string>
37 #include <stdio.h>
38 #include <stdarg.h>
41 namespace Inkscape
42 {
43 namespace Extension
44 {
45 namespace Internal
46 {
51 //########################################################################
52 //# U T I L I T Y
53 //########################################################################
57 /**
58  * This function searches the Repr tree recursively from the given node,
59  * and adds refs to all nodes with the given name, to the result vector
60  */
61 static void
62 findElementsByTagName(std::vector<Inkscape::XML::Node *> &results,
63                       Inkscape::XML::Node *node,
64                       char const *name)
65 {
66     if ( !name || strcmp(node->name(), name) == 0 )
67         results.push_back(node);
69     for (Inkscape::XML::Node *child = node->firstChild() ; child ;
70               child = child->next())
71         findElementsByTagName( results, child, name );
73 }
79 static double
80 effective_opacity(SPItem const *item)
81 {
82     double ret = 1.0;
83     for (SPObject const *obj = item; obj; obj = obj->parent)
84         {
85         SPStyle const *const style = SP_OBJECT_STYLE(obj);
86         g_return_val_if_fail(style, ret);
87         ret *= SP_SCALE24_TO_FLOAT(style->opacity.value);
88         }
89     return ret;
90 }
96 //########################################################################
97 //# OUTPUT FORMATTING
98 //########################################################################
101 /**
102  * We want to control floating output format
103  */
104 static PovOutput::String dstr(double d)
106     char dbuf[G_ASCII_DTOSTR_BUF_SIZE+1];
107     g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE,
108                   "%.8f", (gdouble)d);
109     PovOutput::String s = dbuf;
110     return s;
116 /**
117  *  Output data to the buffer, printf()-style
118  */
119 void PovOutput::out(const char *fmt, ...)
121     va_list args;
122     va_start(args, fmt);
123     gchar *output = g_strdup_vprintf(fmt, args);
124     va_end(args);
125     outbuf.append(output);
126     g_free(output);
133 /**
134  *  Output a 2d vector
135  */
136 void PovOutput::vec2(double a, double b)
138     out("<%s, %s>", dstr(a).c_str(), dstr(b).c_str());
143 /**
144  * Output a 3d vector
145  */
146 void PovOutput::vec3(double a, double b, double c)
148     out("<%s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(), dstr(c).c_str());
153 /**
154  *  Output a v4d ector
155  */
156 void PovOutput::vec4(double a, double b, double c, double d)
158     out("<%s, %s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(),
159                  dstr(c).c_str(), dstr(d).c_str());
164 /**
165  *  Output an rgbf color vector
166  */
167 void PovOutput::rgbf(double r, double g, double b, double f)
169     //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
170     out("rgbf ");
171     vec4(r, g, b, f);
176 /**
177  *  Output one bezier's start, start-control, end-control, and end nodes
178  */
179 void PovOutput::segment(int segNr,
180                         double startX,     double startY,
181                         double startCtrlX, double startCtrlY,
182                         double endCtrlX,   double endCtrlY,
183                         double endX,       double endY)
185     //"    /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
186     out("    /*%4d*/ ", segNr);
187     vec2(startX,     startY);
188     out(", ");
189     vec2(startCtrlX, startCtrlY);
190     out(", ");
191     vec2(endCtrlX,   endCtrlY);
192     out(", ");
193     vec2(endX,       endY);
200 /**
201  * Output the file header
202  */
203 void PovOutput::doHeader()
205     time_t tim = time(NULL);
206     out("/*###################################################################\n");
207     out("### This PovRay document was generated by Inkscape\n");
208     out("### http://www.inkscape.org\n");
209     out("### Created: %s", ctime(&tim));
210     out("### Version: %s\n", INKSCAPE_VERSION);
211     out("#####################################################################\n");
212     out("### NOTES:\n");
213     out("### ============\n");
214     out("### POVRay information can be found at\n");
215     out("### http://www.povray.org\n");
216     out("###\n");
217     out("### The 'AllShapes' objects at the bottom are provided as a\n");
218     out("### preview of how the output would look in a trace.  However,\n");
219     out("### the main intent of this file is to provide the individual\n");
220     out("### shapes for inclusion in a POV project.\n");
221     out("###\n");
222     out("### For an example of how to use this file, look at\n");
223     out("### share/examples/istest.pov\n");
224     out("###\n");
225     out("### If you have any problems with this output, please see the\n");
226     out("### Inkscape project at http://www.inkscape.org, or visit\n");
227     out("### the #inkscape channel on irc.freenode.net . \n");
228     out("###\n");
229     out("###################################################################*/\n");
230     out("\n\n");
231     out("/*###################################################################\n");
232     out("##   Exports in this file\n");
233     out("##==========================\n");
234     out("##    Shapes   : %d\n", nrShapes);
235     out("##    Segments : %d\n", nrSegments);
236     out("##    Nodes    : %d\n", nrNodes);
237     out("###################################################################*/\n");
238     out("\n\n\n");
243 /**
244  *  Output the file footer
245  */
246 void PovOutput::doTail()
248     out("\n\n");
249     out("/*###################################################################\n");
250     out("### E N D    F I L E\n");
251     out("###################################################################*/\n");
252     out("\n\n");
257 /**
258  *  Output the curve data to buffer
259  */
260 void PovOutput::doCurves(SPDocument *doc)
262     using Geom::X;
263     using Geom::Y;
265     std::vector<Inkscape::XML::Node *>results;
266     //findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, "path");
267     findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, NULL);
268     if (results.size() == 0)
269         return;
271     double bignum = 1000000.0;
272     double minx  =  bignum;
273     double maxx  = -bignum;
274     double miny  =  bignum;
275     double maxy  = -bignum;
277     for (unsigned int indx = 0; indx < results.size() ; indx++)
278         {
279         //### Fetch the object from the repr info
280         Inkscape::XML::Node *rpath = results[indx];
281         char *str  = (char *) rpath->attribute("id");
282         if (!str)
283             continue;
285         String id = str;
286         SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(rpath);
287         if (!reprobj)
288             continue;
290         //### Get the transform of the item
291         if (!SP_IS_ITEM(reprobj))
292             continue;
294         SPItem *item = SP_ITEM(reprobj);
295         Geom::Matrix tf = sp_item_i2d_affine(item);
297         //### Get the Shape
298         if (!SP_IS_SHAPE(reprobj))//Bulia's suggestion.  Allow all shapes
299             continue;
301         SPShape *shape = SP_SHAPE(reprobj);
302         SPCurve *curve = shape->curve;
303         if (curve->is_empty())
304             continue;
305             
306         nrShapes++;
308         PovShapeInfo shapeInfo;
309         shapeInfo.id    = id;
310         shapeInfo.color = "";
312         //Try to get the fill color of the shape
313         SPStyle *style = SP_OBJECT_STYLE(shape);
314         /* fixme: Handle other fill types, even if this means translating gradients to a single
315            flat colour. */
316         if (style && (style->fill.isColor()))
317             {
318             // see color.h for how to parse SPColor
319             float rgb[3];
320             sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
321             double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
322                                       * effective_opacity(shape) );
323             //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
324             //                             rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
325             String rgbf = "rgbf <";
326             rgbf.append(dstr(rgb[0]));         rgbf.append(", ");
327             rgbf.append(dstr(rgb[1]));         rgbf.append(", ");
328             rgbf.append(dstr(rgb[2]));         rgbf.append(", ");
329             rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
330             shapeInfo.color += rgbf;
331             }
333         povShapes.push_back(shapeInfo); //passed all tests.  save the info
335         // convert the path to only lineto's and cubic curveto's:
336         Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curve->get_pathvector() * tf );
338         //Count the NR_CURVETOs/LINETOs (including closing line segment)
339         guint segmentCount = 0;
340         for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it) {
341             segmentCount += (*it).size();
342             if (it->closed())
343                 segmentCount += 1;
344         }
346         out("/*###################################################\n");
347         out("### PRISM:  %s\n", id.c_str());
348         out("###################################################*/\n");
349         out("#declare %s = prism {\n", id.c_str());
350         out("    linear_sweep\n");
351         out("    bezier_spline\n");
352         out("    1.0, //top\n");
353         out("    0.0, //bottom\n");
354         out("    %d //nr points\n", segmentCount * 4);
355         int segmentNr = 0;
357         nrSegments += segmentCount;
359         Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() );  // at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
360         for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
362             cminmax.expandTo(pit->initialPoint());
364             for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit) {
366                 if( dynamic_cast<Geom::LineSegment const *> (&*cit) ||
367                     dynamic_cast<Geom::HLineSegment const *>(&*cit) ||
368                     dynamic_cast<Geom::VLineSegment const *>(&*cit) )
369                 {
370                     segment(segmentNr++,
371                             cit->initialPoint()[X], cit->initialPoint()[Y], cit->initialPoint()[X], cit->initialPoint()[Y],
372                             cit->finalPoint()[X], cit->finalPoint()[Y], cit->finalPoint()[X], cit->finalPoint()[Y] );
373                     nrNodes += 8;
374                 }
375                 else if(Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const*>(&*cit)) {
376                     std::vector<Geom::Point> points = cubic->points();
377                     segment(segmentNr++,
378                             points[0][X],points[0][Y], points[1][X],points[1][Y], points[2][X],points[2][Y], points[3][X],points[3][Y]);
379                     nrNodes += 8;
380                 }
381                 else {
382                     g_error ("logical error, because pathv_to_linear_and_cubic_beziers was used");
383                 }
385                 if (segmentNr <= segmentCount)
386                     out(",\n");
387                 else
388                     out("\n");
390                 cminmax.expandTo(cit->finalPoint());
392             }
393         }
395         out("}\n");
397         double cminx = cminmax.min()[X];
398         double cmaxx = cminmax.max()[X];
399         double cminy = cminmax.min()[Y];
400         double cmaxy = cminmax.max()[Y];
401                      
402         //# prefix for following declarations
403         char *pfx = (char *)id.c_str();
405         out("#declare %s_MIN_X    = %s;\n", pfx, dstr(cminx).c_str());
406         out("#declare %s_CENTER_X = %s;\n", pfx, dstr((cmaxx+cminx)/2.0).c_str());
407         out("#declare %s_MAX_X    = %s;\n", pfx, dstr(cmaxx).c_str());
408         out("#declare %s_WIDTH    = %s;\n", pfx, dstr(cmaxx-cminx).c_str());
409         out("#declare %s_MIN_Y    = %s;\n", pfx, dstr(cminy).c_str());
410         out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((cmaxy+cminy)/2.0).c_str());
411         out("#declare %s_MAX_Y    = %s;\n", pfx, dstr(cmaxy).c_str());
412         out("#declare %s_HEIGHT   = %s;\n", pfx, dstr(cmaxy-cminy).c_str());
413         if (shapeInfo.color.length()>0)
414             out("#declare %s_COLOR    = %s;\n",
415                     pfx, shapeInfo.color.c_str());
416         out("/*###################################################\n");
417         out("### end %s\n", id.c_str());
418         out("###################################################*/\n\n\n\n");
419         if (cminx < minx)
420             minx = cminx;
421         if (cmaxx > maxx)
422             maxx = cmaxx;
423         if (cminy < miny)
424             miny = cminy;
425         if (cmaxy > maxy)
426             maxy = cmaxy;
428         }//for
432     //## Let's make a union of all of the Shapes
433     if (povShapes.size()>0)
434         {
435         String id = "AllShapes";
436         char *pfx = (char *)id.c_str();
437         out("/*###################################################\n");
438         out("### UNION OF ALL SHAPES IN DOCUMENT\n");
439         out("###################################################*/\n");
440         out("\n\n");
441         out("/**\n");
442         out(" * Allow the user to redefine the finish{}\n");
443         out(" * by declaring it before #including this file\n");
444         out(" */\n");
445         out("#ifndef (%s_Finish)\n", pfx);
446         out("#declare %s_Finish = finish {\n", pfx);
447         out("    phong 0.5\n");
448         out("    reflection 0.3\n");
449         out("    specular 0.5\n");
450         out("}\n");
451         out("#end\n");
452         out("\n\n");
453         out("#declare %s = union {\n", id.c_str());
454         for (unsigned i = 0 ; i < povShapes.size() ; i++)
455             {
456             out("    object { %s\n", povShapes[i].id.c_str());
457             out("        texture { \n");
458             if (povShapes[i].color.length()>0)
459                 out("            pigment { %s }\n", povShapes[i].color.c_str());
460             else
461                 out("            pigment { rgb <0,0,0> }\n");
462             out("            finish { %s_Finish }\n", pfx);
463             out("            } \n");
464             out("        } \n");
465             }
466         out("}\n\n\n\n");
469         double zinc   = 0.2 / (double)povShapes.size();
470         out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
471         out("\n\n");
472         out("/**\n");
473         out(" * Allow the user to redefine the Z-Increment\n");
474         out(" */\n");
475         out("#ifndef (AllShapes_Z_Increment)\n");
476         out("#declare AllShapes_Z_Increment = %s;\n", dstr(zinc).c_str());
477         out("#end\n");
478         out("\n");
479         out("#declare AllShapes_Z_Scale = 1.0;\n");
480         out("\n\n");
481         out("#declare %s_Z = union {\n", pfx);
483         for (unsigned i = 0 ; i < povShapes.size() ; i++)
484             {
485             out("    object { %s\n", povShapes[i].id.c_str());
486             out("        texture { \n");
487             if (povShapes[i].color.length()>0)
488                 out("            pigment { %s }\n", povShapes[i].color.c_str());
489             else
490                 out("            pigment { rgb <0,0,0> }\n");
491             out("            finish { %s_Finish }\n", pfx);
492             out("            } \n");
493             out("        scale <1, %s_Z_Scale, 1>\n", pfx);
494             out("        } \n");
495             out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
496                     pfx, pfx, pfx);
497             }
499         out("}\n");
501         out("#declare %s_MIN_X    = %s;\n", pfx, dstr(minx).c_str());
502         out("#declare %s_CENTER_X = %s;\n", pfx, dstr((maxx+minx)/2.0).c_str());
503         out("#declare %s_MAX_X    = %s;\n", pfx, dstr(maxx).c_str());
504         out("#declare %s_WIDTH    = %s;\n", pfx, dstr(maxx-minx).c_str());
505         out("#declare %s_MIN_Y    = %s;\n", pfx, dstr(miny).c_str());
506         out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((maxy+miny)/2.0).c_str());
507         out("#declare %s_MAX_Y    = %s;\n", pfx, dstr(maxy).c_str());
508         out("#declare %s_HEIGHT   = %s;\n", pfx, dstr(maxy-miny).c_str());
509         out("/*##############################################\n");
510         out("### end %s\n", id.c_str());
511         out("##############################################*/\n");
512         out("\n\n");
513         }
520 //########################################################################
521 //# M A I N    O U T P U T
522 //########################################################################
526 /**
527  *  Set values back to initial state
528  */
529 void PovOutput::reset()
531     nrNodes    = 0;
532     nrSegments = 0;
533     nrShapes   = 0;
534     outbuf.clear();
535     povShapes.clear();
540 /**
541  * Saves the <paths> of an Inkscape SVG file as PovRay spline definitions
542  */
543 void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
545     reset();
547     //###### SAVE IN POV FORMAT TO BUFFER
548     //# Lets do the curves first, to get the stats
549     doCurves(doc);
550     String curveBuf = outbuf;
551     outbuf.clear();
553     doHeader();
554     
555     outbuf.append(curveBuf);
556     
557     doTail();
562     //###### WRITE TO FILE
563     Inkscape::IO::dump_fopen_call(uri, "L");
564     FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
565     if (!f)
566         return;
568     for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
569         {
570         int ch = *iter;
571         fputc(ch, f);
572         }
573         
574     fclose(f);
580 //########################################################################
581 //# EXTENSION API
582 //########################################################################
586 #include "clear-n_.h"
590 /**
591  * API call to save document
592 */
593 void
594 PovOutput::save(Inkscape::Extension::Output *mod,
595                         SPDocument *doc, gchar const *uri)
597     saveDocument(doc, uri);
602 /**
603  * Make sure that we are in the database
604  */
605 bool PovOutput::check (Inkscape::Extension::Extension *module)
607     /* We don't need a Key
608     if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
609         return FALSE;
610     */
612     return true;
617 /**
618  * This is the definition of PovRay output.  This function just
619  * calls the extension system with the memory allocated XML that
620  * describes the data.
621 */
622 void
623 PovOutput::init()
625     Inkscape::Extension::build_from_mem(
626         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
627             "<name>" N_("PovRay Output") "</name>\n"
628             "<id>org.inkscape.output.pov</id>\n"
629             "<output>\n"
630                 "<extension>.pov</extension>\n"
631                 "<mimetype>text/x-povray-script</mimetype>\n"
632                 "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
633                 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
634             "</output>\n"
635         "</inkscape-extension>",
636         new PovOutput());
643 }  // namespace Internal
644 }  // namespace Extension
645 }  // namespace Inkscape
648 /*
649   Local Variables:
650   mode:c++
651   c-file-style:"stroustrup"
652   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
653   indent-tabs-mode:nil
654   fill-column:99
655   End:
656 */
657 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :