c915de75bfb3dbf34dcb8c65acb24c0070238d03
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 <ishmalius@gmail.com>
13 *
14 * Copyright (C) 2004-2007 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 "sp-path.h"
26 #include <style.h>
27 #include "display/curve.h"
28 #include "libnr/n-art-bpath.h"
29 #include "extension/system.h"
31 #include "io/sys.h"
33 #include <string>
34 #include <stdio.h>
35 #include <stdarg.h>
38 namespace Inkscape
39 {
40 namespace Extension
41 {
42 namespace Internal
43 {
48 //########################################################################
49 //# U T I L I T Y
50 //########################################################################
54 /**
55 * This function searches the Repr tree recursively from the given node,
56 * and adds refs to all nodes with the given name, to the result vector
57 */
58 static void
59 findElementsByTagName(std::vector<Inkscape::XML::Node *> &results,
60 Inkscape::XML::Node *node,
61 char const *name)
62 {
63 if ( !name || strcmp(node->name(), name) == 0 )
64 results.push_back(node);
66 for (Inkscape::XML::Node *child = node->firstChild() ; child ;
67 child = child->next())
68 findElementsByTagName( results, child, name );
70 }
76 static double
77 effective_opacity(SPItem const *item)
78 {
79 double ret = 1.0;
80 for (SPObject const *obj = item; obj; obj = obj->parent)
81 {
82 SPStyle const *const style = SP_OBJECT_STYLE(obj);
83 g_return_val_if_fail(style, ret);
84 ret *= SP_SCALE24_TO_FLOAT(style->opacity.value);
85 }
86 return ret;
87 }
93 //########################################################################
94 //# OUTPUT FORMATTING
95 //########################################################################
97 static const char *formatDouble(gchar *sbuffer, double d)
98 {
99 return (const char *)g_ascii_formatd(sbuffer,
100 G_ASCII_DTOSTR_BUF_SIZE, "%.8g", (gdouble)d);
102 }
105 /**
106 * Not-threadsafe version
107 */
108 static char _dstr_buf[G_ASCII_DTOSTR_BUF_SIZE+1];
110 static const char *dstr(double d)
111 {
112 return formatDouble(_dstr_buf, d);
113 }
120 /**
121 * Output data to the buffer, printf()-style
122 */
123 void PovOutput::out(char *fmt, ...)
124 {
125 va_list args;
126 va_start(args, fmt);
127 gchar * output = g_strdup_vprintf(fmt, args);
128 va_end(args);
129 outbuf.append(output);
130 g_free(output);
131 }
139 /**
140 * Output a 3d vector
141 */
142 void PovOutput::vec2(double a, double b)
143 {
144 outbuf.append("<");
145 outbuf.append(dstr(a));
146 outbuf.append(", ");
147 outbuf.append(dstr(b));
148 outbuf.append(">");
149 }
153 /**
154 * Output a 3d vector
155 */
156 void PovOutput::vec3(double a, double b, double c)
157 {
158 outbuf.append("<");
159 outbuf.append(dstr(a));
160 outbuf.append(", ");
161 outbuf.append(dstr(b));
162 outbuf.append(", ");
163 outbuf.append(dstr(c));
164 outbuf.append(">");
165 }
169 /**
170 * Output a v4d ector
171 */
172 void PovOutput::vec4(double a, double b, double c, double d)
173 {
174 outbuf.append("<");
175 outbuf.append(dstr(a));
176 outbuf.append(", ");
177 outbuf.append(dstr(b));
178 outbuf.append(", ");
179 outbuf.append(dstr(c));
180 outbuf.append(", ");
181 outbuf.append(dstr(d));
182 outbuf.append(">");
183 }
186 /**
187 * Output an rgbf color vector
188 */
189 void PovOutput::rgbf(double r, double g, double b, double f)
190 {
191 //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
192 outbuf.append("rgbf ");
193 vec4(r, g, b, f);
194 }
198 /**
199 * Output one bezier's start, start-control, end-control, and end nodes
200 */
201 void PovOutput::segment(int segNr, double a0, double a1,
202 double b0, double b1,
203 double c0, double c1,
204 double d0, double d1)
205 {
206 //" /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
207 char buf[32];
208 snprintf(buf, 31, " /*%4d*/ ", segNr);
209 outbuf.append(buf);
210 vec2(a0, a1);
211 outbuf.append(", ");
212 vec2(b0, b1);
213 outbuf.append(", ");
214 vec2(c0, c1);
215 outbuf.append(", ");
216 vec2(d0, d1);
217 }
223 /**
224 * Output the file header
225 */
226 void PovOutput::doHeader()
227 {
228 time_t tim = time(NULL);
229 out("/*###################################################################\n");
230 out("### This PovRay document was generated by Inkscape\n");
231 out("### http://www.inkscape.org\n");
232 out("### Created: %s", ctime(&tim));
233 out("### Version: %s\n", VERSION);
234 out("#####################################################################\n");
235 out("### NOTES:\n");
236 out("### ============\n");
237 out("### POVRay information can be found at\n");
238 out("### http://www.povray.org\n");
239 out("###\n");
240 out("### The 'AllShapes' objects at the bottom are provided as a\n");
241 out("### preview of how the output would look in a trace. However,\n");
242 out("### the main intent of this file is to provide the individual\n");
243 out("### shapes for inclusion in a POV project.\n");
244 out("###\n");
245 out("### For an example of how to use this file, look at\n");
246 out("### share/examples/istest.pov\n");
247 out("###################################################################*/\n");
248 out("\n\n");
249 out("/*###################################################################\n");
250 out("## Exports in this file\n");
251 out("##==========================\n");
252 out("## Shapes : %d\n", nrShapes);
253 out("## Segments : %d\n", nrSegments);
254 out("## Nodes : %d\n", nrNodes);
255 out("###################################################################*/\n");
256 out("\n\n\n");
257 }
261 /**
262 * Output the file footer
263 */
264 void PovOutput::doTail()
265 {
266 out("\n\n");
267 out("/*###################################################################\n");
268 out("### E N D F I L E\n");
269 out("###################################################################*/\n");
270 out("\n\n");
271 }
275 /**
276 * Output the curve data to buffer
277 */
278 void PovOutput::doCurves(SPDocument *doc)
279 {
280 std::vector<Inkscape::XML::Node *>results;
281 //findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, "path");
282 findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, NULL);
283 if (results.size() == 0)
284 return;
286 double bignum = 1000000.0;
287 double minx = bignum;
288 double maxx = -bignum;
289 double miny = bignum;
290 double maxy = -bignum;
292 for (unsigned int indx = 0; indx < results.size() ; indx++)
293 {
294 //### Fetch the object from the repr info
295 Inkscape::XML::Node *rpath = results[indx];
296 char *str = (char *) rpath->attribute("id");
297 if (!str)
298 continue;
300 String id = str;
301 SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(rpath);
302 if (!reprobj)
303 continue;
305 //### Get the transform of the item
306 if (!SP_IS_ITEM(reprobj))
307 continue;
309 SPItem *item = SP_ITEM(reprobj);
310 NR::Matrix tf = sp_item_i2d_affine(item);
312 //### Get the Shape
313 if (!SP_IS_SHAPE(reprobj))//Bulia's suggestion. Allow all shapes
314 continue;
316 SPShape *shape = SP_SHAPE(reprobj);
317 SPCurve *curve = shape->curve;
318 if (sp_curve_empty(curve))
319 continue;
321 nrShapes++;
323 PovShapeInfo shapeInfo;
324 shapeInfo.id = id;
325 shapeInfo.color = "";
327 //Try to get the fill color of the shape
328 SPStyle *style = SP_OBJECT_STYLE(shape);
329 /* fixme: Handle other fill types, even if this means translating gradients to a single
330 flat colour. */
331 if (style && (style->fill.isColor()))
332 {
333 // see color.h for how to parse SPColor
334 float rgb[3];
335 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
336 double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
337 * effective_opacity(shape) );
338 //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
339 // rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
340 String rgbf = "rgbf <";
341 rgbf.append(dstr(rgb[0])); rgbf.append(", ");
342 rgbf.append(dstr(rgb[1])); rgbf.append(", ");
343 rgbf.append(dstr(rgb[2])); rgbf.append(", ");
344 rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
345 shapeInfo.color += rgbf;
346 }
348 povShapes.push_back(shapeInfo); //passed all tests. save the info
350 int curveLength = SP_CURVE_LENGTH(curve);
352 //Count the NR_CURVETOs/LINETOs
353 int segmentCount=0;
354 NArtBpath *bp = SP_CURVE_BPATH(curve);
355 for (int curveNr=0 ; curveNr<curveLength ; curveNr++, bp++)
356 if (bp->code == NR_CURVETO || bp->code == NR_LINETO)
357 segmentCount++;
359 double cminx = bignum;
360 double cmaxx = -bignum;
361 double cminy = bignum;
362 double cmaxy = -bignum;
363 double lastx = 0.0;
364 double lasty = 0.0;
366 out("/*###################################################\n");
367 out("### PRISM: %s\n", id.c_str());
368 out("###################################################*/\n");
369 out("#declare %s = prism {\n", id.c_str());
370 out(" linear_sweep\n");
371 out(" bezier_spline\n");
372 out(" 1.0, //top\n");
373 out(" 0.0, //bottom\n");
374 out(" %d //nr points\n", segmentCount * 4);
375 int segmentNr = 0;
376 bp = SP_CURVE_BPATH(curve);
378 nrSegments += curveLength;
380 for (int curveNr=0 ; curveNr < curveLength ; curveNr++)
381 {
382 using NR::X;
383 using NR::Y;
384 NR::Point const p1(bp->c(1) * tf);
385 NR::Point const p2(bp->c(2) * tf);
386 NR::Point const p3(bp->c(3) * tf);
387 double const x1 = p1[X], y1 = p1[Y];
388 double const x2 = p2[X], y2 = p2[Y];
389 double const x3 = p3[X], y3 = p3[Y];
391 switch (bp->code)
392 {
393 case NR_MOVETO:
394 case NR_MOVETO_OPEN:
395 {
396 //fprintf(f, "moveto: %f %f\n", bp->x3, bp->y3);
397 break;
398 }
399 case NR_CURVETO:
400 {
401 //fprintf(f, " /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>",
402 // segmentNr++, lastx, lasty, x1, y1, x2, y2, x3, y3);
403 segment(segmentNr++,
404 lastx, lasty, x1, y1, x2, y2, x3, y3);
405 nrNodes += 8;
407 if (segmentNr < segmentCount)
408 out(",\n");
409 else
410 out("\n");
412 if (lastx < cminx)
413 cminx = lastx;
414 if (lastx > cmaxx)
415 cmaxx = lastx;
416 if (lasty < cminy)
417 cminy = lasty;
418 if (lasty > cmaxy)
419 cmaxy = lasty;
420 break;
421 }
422 case NR_LINETO:
423 {
424 //fprintf(f, " /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>",
425 // segmentNr++, lastx, lasty, lastx, lasty, x3, y3, x3, y3);
426 segment(segmentNr++,
427 lastx, lasty, lastx, lasty, x3, y3, x3, y3);
428 nrNodes += 8;
430 if (segmentNr < segmentCount)
431 out(",\n");
432 else
433 out("\n");
435 //fprintf(f, "lineto\n");
436 if (lastx < cminx)
437 cminx = lastx;
438 if (lastx > cmaxx)
439 cmaxx = lastx;
440 if (lasty < cminy)
441 cminy = lasty;
442 if (lasty > cmaxy)
443 cmaxy = lasty;
444 break;
445 }
446 case NR_END:
447 {
448 //fprintf(f, "end\n");
449 break;
450 }
451 }
452 lastx = x3;
453 lasty = y3;
454 bp++;
455 }
456 out("}\n");
459 char *pfx = (char *)id.c_str();
461 out("#declare %s_MIN_X = %s;\n", pfx, dstr(cminx));
462 out("#declare %s_CENTER_X = %s;\n", pfx, dstr((cmaxx+cminx)/2.0));
463 out("#declare %s_MAX_X = %s;\n", pfx, dstr(cmaxx));
464 out("#declare %s_WIDTH = %s;\n", pfx, dstr(cmaxx-cminx));
465 out("#declare %s_MIN_Y = %s;\n", pfx, dstr(cminy));
466 out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((cmaxy+cminy)/2.0));
467 out("#declare %s_MAX_Y = %s;\n", pfx, dstr(cmaxy));
468 out("#declare %s_HEIGHT = %s;\n", pfx, dstr(cmaxy-cminy));
469 if (shapeInfo.color.length()>0)
470 out("#declare %s_COLOR = %s;\n",
471 pfx, shapeInfo.color.c_str());
472 out("/*###################################################\n");
473 out("### end %s\n", id.c_str());
474 out("###################################################*/\n\n\n\n");
475 if (cminx < minx)
476 minx = cminx;
477 if (cmaxx > maxx)
478 maxx = cmaxx;
479 if (cminy < miny)
480 miny = cminy;
481 if (cmaxy > maxy)
482 maxy = cmaxy;
484 }//for
488 //## Let's make a union of all of the Shapes
489 if (povShapes.size()>0)
490 {
491 String id = "AllShapes";
492 char *pfx = (char *)id.c_str();
493 out("/*###################################################\n");
494 out("### UNION OF ALL SHAPES IN DOCUMENT\n");
495 out("###################################################*/\n");
496 out("\n\n");
497 out("/**\n");
498 out(" * Allow the user to redefine the finish{}\n");
499 out(" * by declaring it before #including this file\n");
500 out(" */\n");
501 out("#ifndef (%s_Finish)\n", pfx);
502 out("#declare %s_Finish = finish {\n", pfx);
503 out(" phong 0.5\n");
504 out(" reflection 0.3\n");
505 out(" specular 0.5\n");
506 out("}\n");
507 out("#end\n");
508 out("\n\n");
509 out("#declare %s = union {\n", id.c_str());
510 for (unsigned i = 0 ; i < povShapes.size() ; i++)
511 {
512 out(" object { %s\n", povShapes[i].id.c_str());
513 out(" texture { \n");
514 if (povShapes[i].color.length()>0)
515 out(" pigment { %s }\n", povShapes[i].color.c_str());
516 else
517 out(" pigment { rgb <0,0,0> }\n");
518 out(" finish { %s_Finish }\n", pfx);
519 out(" } \n");
520 out(" } \n");
521 }
522 out("}\n\n\n\n");
525 double zinc = 0.2 / (double)povShapes.size();
526 out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
527 out("\n\n");
528 out("/**\n");
529 out(" * Allow the user to redefine the Z-Increment\n");
530 out(" */\n");
531 out("#ifndef (AllShapes_Z_Increment)\n");
532 out("#declare AllShapes_Z_Increment = %s;\n", dstr(zinc));
533 out("#end\n");
534 out("\n");
535 out("#declare AllShapes_Z_Scale = 1.0;\n");
536 out("\n\n");
537 out("#declare %s_Z = union {\n", pfx);
539 for (unsigned i = 0 ; i < povShapes.size() ; i++)
540 {
541 out(" object { %s\n", povShapes[i].id.c_str());
542 out(" texture { \n");
543 if (povShapes[i].color.length()>0)
544 out(" pigment { %s }\n", povShapes[i].color.c_str());
545 else
546 out(" pigment { rgb <0,0,0> }\n");
547 out(" finish { %s_Finish }\n", pfx);
548 out(" } \n");
549 out(" scale <1, %s_Z_Scale, 1>\n", pfx);
550 out(" } \n");
551 out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
552 pfx, pfx, pfx);
553 }
555 out("}\n");
557 out("#declare %s_MIN_X = %s;\n", pfx, dstr(minx));
558 out("#declare %s_CENTER_X = %s;\n", pfx, dstr((maxx+minx)/2.0));
559 out("#declare %s_MAX_X = %s;\n", pfx, dstr(maxx));
560 out("#declare %s_WIDTH = %s;\n", pfx, dstr(maxx-minx));
561 out("#declare %s_MIN_Y = %s;\n", pfx, dstr(miny));
562 out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((maxy+miny)/2.0));
563 out("#declare %s_MAX_Y = %s;\n", pfx, dstr(maxy));
564 out("#declare %s_HEIGHT = %s;\n", pfx, dstr(maxy-miny));
565 out("/*##############################################\n");
566 out("### end %s\n", id.c_str());
567 out("##############################################*/\n");
568 out("\n\n");
569 }
571 }
576 //########################################################################
577 //# M A I N O U T P U T
578 //########################################################################
582 /**
583 * Set values back to initial state
584 */
585 void PovOutput::reset()
586 {
587 nrNodes = 0;
588 nrSegments = 0;
589 nrShapes = 0;
590 outbuf.clear();
591 povShapes.clear();
592 }
596 /**
597 * Saves the <paths> of an Inkscape SVG file as PovRay spline definitions
598 */
599 void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
600 {
601 reset();
603 //###### SAVE IN POV FORMAT TO BUFFER
604 //# Lets do the curves first, to get the stats
605 doCurves(doc);
606 String curveBuf = outbuf;
607 outbuf.clear();
609 doHeader();
611 outbuf.append(curveBuf);
613 doTail();
618 //###### WRITE TO FILE
619 Inkscape::IO::dump_fopen_call(uri, "L");
620 FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
621 if (!f)
622 return;
624 for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
625 {
626 int ch = *iter;
627 fputc(ch, f);
628 }
630 fclose(f);
631 }
636 //########################################################################
637 //# EXTENSION API
638 //########################################################################
642 #include "clear-n_.h"
646 /**
647 * API call to save document
648 */
649 void
650 PovOutput::save(Inkscape::Extension::Output *mod,
651 SPDocument *doc, gchar const *uri)
652 {
653 saveDocument(doc, uri);
654 }
658 /**
659 * Make sure that we are in the database
660 */
661 bool PovOutput::check (Inkscape::Extension::Extension *module)
662 {
663 /* We don't need a Key
664 if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
665 return FALSE;
666 */
668 return true;
669 }
673 /**
674 * This is the definition of PovRay output. This function just
675 * calls the extension system with the memory allocated XML that
676 * describes the data.
677 */
678 void
679 PovOutput::init()
680 {
681 Inkscape::Extension::build_from_mem(
682 "<inkscape-extension>\n"
683 "<name>" N_("PovRay Output") "</name>\n"
684 "<id>org.inkscape.output.pov</id>\n"
685 "<output>\n"
686 "<extension>.pov</extension>\n"
687 "<mimetype>text/x-povray-script</mimetype>\n"
688 "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
689 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
690 "</output>\n"
691 "</inkscape-extension>",
692 new PovOutput());
693 }
699 } // namespace Internal
700 } // namespace Extension
701 } // namespace Inkscape
704 /*
705 Local Variables:
706 mode:c++
707 c-file-style:"stroustrup"
708 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
709 indent-tabs-mode:nil
710 fill-column:99
711 End:
712 */
713 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :