1 // An OpenVG path on the Canvas
3 // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Library General Public License for more details.
15 // You should have received a copy of the GNU Library General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 #include "CanvasPath.hxx"
20 #include <simgear/scene/util/parse_color.hxx>
22 #include <osg/Drawable>
23 #include <osg/BlendFunc>
25 #include <vg/openvg.h>
32 typedef std::vector<VGubyte> CmdList;
33 typedef std::vector<VGfloat> CoordList;
36 static const VGubyte shCoordsPerCommand[] = {
37 0, /* VG_CLOSE_PATH */
46 5, /* VG_SCCWARC_TO */
48 5, /* VG_LCCWARC_TO */
51 static const VGubyte shNumCommands = sizeof(shCoordsPerCommand)
52 / sizeof(shCoordsPerCommand[0]);
55 * Helper to split and convert comma/whitespace separated floating point
58 std::vector<float> splitAndConvert(const char del[], const std::string& str);
60 class Path::PathDrawable:
64 PathDrawable(Path* path):
66 _path(VG_INVALID_HANDLE),
67 _paint(VG_INVALID_HANDLE),
68 _paint_fill(VG_INVALID_HANDLE),
69 _attributes_dirty(~0),
71 _fill_rule(VG_EVEN_ODD),
73 _stroke_linecap(VG_CAP_BUTT)
75 setSupportsDisplayList(false);
76 setDataVariance(Object::DYNAMIC);
78 setUpdateCallback(new PathUpdateCallback());
81 virtual ~PathDrawable()
83 if( _path != VG_INVALID_HANDLE )
85 if( _paint != VG_INVALID_HANDLE )
86 vgDestroyPaint(_paint);
87 if( _paint_fill != VG_INVALID_HANDLE )
88 vgDestroyPaint(_paint_fill);
91 virtual const char* className() const { return "PathDrawable"; }
92 virtual osg::Object* cloneType() const { return new PathDrawable(_path_element); }
93 virtual osg::Object* clone(const osg::CopyOp&) const { return new PathDrawable(_path_element); }
96 * Replace the current path segments with the new ones
98 * @param cmds List of OpenVG path commands
99 * @param coords List of coordinates/parameters used by #cmds
101 void setSegments(const CmdList& cmds, const CoordList& coords)
106 _attributes_dirty |= (PATH | BOUNDING_BOX);
110 * Set path fill paint ("none" if not filled)
112 void setFill(const std::string& fill)
116 _mode &= ~VG_FILL_PATH;
118 else if( parseColor(fill, _fill_color) )
120 _mode |= VG_FILL_PATH;
121 _attributes_dirty |= FILL_COLOR;
129 "canvas::Path Unknown fill: " << fill
135 * Set path fill rule ("pseudo-nonzero" or "evenodd")
137 * @warning As the current nonzero implementation causes sever artifacts
138 * for every concave path we call it pseudo-nonzero, so that
139 * everyone is warned that it won't work as expected :)
141 void setFillRule(const std::string& fill_rule)
143 if( fill_rule == "pseudo-nonzero" )
144 _fill_rule = VG_NON_ZERO;
145 else // if( fill_rule == "evenodd" )
146 _fill_rule = VG_EVEN_ODD;
150 * Set path stroke paint ("none" if no stroke)
152 void setStroke(const std::string& stroke)
154 if( stroke == "none" )
156 _mode &= ~VG_STROKE_PATH;
158 else if( parseColor(stroke, _stroke_color) )
160 _mode |= VG_STROKE_PATH;
161 _attributes_dirty |= STROKE_COLOR;
169 "canvas::Path Unknown stroke: " << stroke
177 void setStrokeWidth(float width)
179 _stroke_width = width;
180 _attributes_dirty |= BOUNDING_BOX;
184 * Set stroke dash (line stipple)
186 void setStrokeDashArray(const std::string& dash)
188 _stroke_dash = splitAndConvert(",\t\n ", dash);
194 * @see http://www.w3.org/TR/SVG/painting.html#StrokeLinecapProperty
196 void setStrokeLinecap(const std::string& linecap)
198 if( linecap == "round" )
199 _stroke_linecap = VG_CAP_ROUND;
200 else if( linecap == "square" )
201 _stroke_linecap = VG_CAP_SQUARE;
203 _stroke_linecap = VG_CAP_BUTT;
209 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
211 if( _attributes_dirty & PATH )
214 osg::State* state = renderInfo.getState();
217 state->setActiveTextureUnit(0);
218 state->setClientActiveTextureUnit(0);
219 state->disableAllVertexArrays();
221 glPushAttrib(~0u); // Don't use GL_ALL_ATTRIB_BITS as on my machine it
222 // eg. doesn't include GL_MULTISAMPLE_BIT
223 glPushClientAttrib(~0u);
225 // Initialize/Update the paint
226 if( _attributes_dirty & STROKE_COLOR )
228 if( _paint == VG_INVALID_HANDLE )
229 _paint = vgCreatePaint();
231 vgSetParameterfv(_paint, VG_PAINT_COLOR, 4, _stroke_color._v);
233 _attributes_dirty &= ~STROKE_COLOR;
236 // Initialize/update fill paint
237 if( _attributes_dirty & FILL_COLOR )
239 if( _paint_fill == VG_INVALID_HANDLE )
240 _paint_fill = vgCreatePaint();
242 vgSetParameterfv(_paint_fill, VG_PAINT_COLOR, 4, _fill_color._v);
244 _attributes_dirty &= ~FILL_COLOR;
248 if( _mode & VG_STROKE_PATH )
250 vgSetPaint(_paint, VG_STROKE_PATH);
252 vgSetf(VG_STROKE_LINE_WIDTH, _stroke_width);
253 vgSeti(VG_STROKE_CAP_STYLE, _stroke_linecap);
254 vgSetfv( VG_STROKE_DASH_PATTERN,
256 _stroke_dash.empty() ? 0 : &_stroke_dash[0] );
258 if( _mode & VG_FILL_PATH )
260 vgSetPaint(_paint_fill, VG_FILL_PATH);
262 vgSeti(VG_FILL_RULE, _fill_rule);
265 // And finally draw the path
267 vgDrawPath(_path, _mode);
269 VGErrorCode err = vgGetError();
270 if( err != VG_NO_ERROR )
271 SG_LOG(SG_GL, SG_ALERT, "vgError: " << err);
277 osg::BoundingBox getTransformedBounds(const osg::Matrix& mat) const
281 osg::Vec2f cur; // VG "Current point" (in local coordinates)
282 VGubyte cmd_index = 0;
283 for( size_t i = 0, ci = 0;
284 i < _cmds.size() && ci < _coords.size();
285 ++i, ci += shCoordsPerCommand[cmd_index] )
287 VGubyte rel = _cmds[i] & 1,
291 if( cmd_index >= shNumCommands )
292 return osg::BoundingBox();
294 const VGubyte max_coords = 3;
295 osg::Vec2f points[max_coords];
296 VGubyte num_coords = 0;
306 points[ num_coords++ ].set(_coords[ci], _coords[ci + 1]);
310 points[ num_coords++ ].set( _coords[ci] + (rel ? cur.x() : 0),
312 // We have handled rel/abs already, so no need to do it again...
317 points[ num_coords++ ].set( cur.x(),
318 _coords[ci] + (rel ? cur.y() : 0) );
319 // We have handled rel/abs already, so no need to do it again...
325 points[ num_coords++ ].set(_coords[ci ], _coords[ci + 1]);
326 points[ num_coords++ ].set(_coords[ci + 2], _coords[ci + 3]);
330 points[ num_coords++ ].set(_coords[ci ], _coords[ci + 1]);
331 points[ num_coords++ ].set(_coords[ci + 2], _coords[ci + 3]);
332 points[ num_coords++ ].set(_coords[ci + 4], _coords[ci + 5]);
339 points[ num_coords++ ].set(_coords[ci + 3], _coords[ci + 4]);
342 SG_LOG(SG_GL, SG_WARN, "Unknown VG command: " << (int)cmd);
343 return osg::BoundingBox();
346 assert(num_coords <= max_coords);
347 for(VGubyte i = 0; i < num_coords; ++i)
352 bb.expandBy( transformPoint(mat, points[i]) );
356 cur = points[ num_coords - 1 ];
363 * Compute the bounding box
365 virtual osg::BoundingBox computeBound() const
367 if( _path == VG_INVALID_HANDLE || (_attributes_dirty & PATH) )
368 return osg::BoundingBox();
370 VGfloat min[2], size[2];
371 vgPathBounds(_path, &min[0], &min[1], &size[0], &size[1]);
373 _attributes_dirty &= ~BOUNDING_BOX;
375 // vgPathBounds doesn't take stroke width into account
376 float ext = 0.5 * _stroke_width;
380 min[0] - ext, min[1] - ext, -0.1,
381 min[0] + size[0] + ext, min[1] + size[1] + ext, 0.1
383 _path_element->setBoundingBox(bb);
393 STROKE_COLOR = PATH << 1,
394 FILL_COLOR = STROKE_COLOR << 1,
395 BOUNDING_BOX = FILL_COLOR << 1
400 mutable VGPath _path;
401 mutable VGPaint _paint;
402 mutable VGPaint _paint_fill;
403 mutable uint32_t _attributes_dirty;
409 osg::Vec4f _fill_color;
410 VGFillRule _fill_rule;
411 osg::Vec4f _stroke_color;
412 VGfloat _stroke_width;
413 std::vector<VGfloat> _stroke_dash;
414 VGCapStyle _stroke_linecap;
416 osg::Vec3f transformPoint( const osg::Matrix& m,
417 osg::Vec2f pos ) const
421 m(0, 0) * pos[0] + m(1, 0) * pos[1] + m(3, 0),
422 m(0, 1) * pos[0] + m(1, 1) * pos[1] + m(3, 1),
428 * Initialize/Update the OpenVG path
432 if( !vgHasContextSH() )
435 if( _attributes_dirty & PATH )
437 const VGbitfield caps = VG_PATH_CAPABILITY_APPEND_TO
438 | VG_PATH_CAPABILITY_MODIFY
439 | VG_PATH_CAPABILITY_PATH_BOUNDS;
441 if( _path == VG_INVALID_HANDLE )
442 _path = vgCreatePath(
443 VG_PATH_FORMAT_STANDARD,
445 1.f, 0.f, // scale,bias
446 _cmds.size(), _coords.size(),
450 vgClearPath(_path, caps);
452 if( !_cmds.empty() && !_coords.empty() )
453 vgAppendPathData(_path, _cmds.size(), &_cmds[0], &_coords[0]);
455 _attributes_dirty &= ~PATH;
456 _attributes_dirty |= BOUNDING_BOX;
459 if( _attributes_dirty & BOUNDING_BOX )
463 struct PathUpdateCallback:
464 public osg::Drawable::UpdateCallback
466 virtual void update(osg::NodeVisitor*, osg::Drawable* drawable)
468 static_cast<PathDrawable*>(drawable)->update();
473 //----------------------------------------------------------------------------
474 Path::Path( const CanvasWeakPtr& canvas,
475 const SGPropertyNode_ptr& node,
476 const Style& parent_style,
478 Element(canvas, node, parent_style, parent),
479 _path( new PathDrawable(this) )
483 if( !isInit<Path>() )
485 PathDrawableRef Path::*path = &Path::_path;
487 addStyle("fill", "color", &PathDrawable::setFill, path);
488 addStyle("fill-rule", "", &PathDrawable::setFillRule, path);
489 addStyle("stroke", "color", &PathDrawable::setStroke, path);
490 addStyle("stroke-width", "numeric", &PathDrawable::setStrokeWidth, path);
491 addStyle("stroke-dasharray", "", &PathDrawable::setStrokeDashArray, path);
492 addStyle("stroke-linecap", "", &PathDrawable::setStrokeLinecap, path);
498 //----------------------------------------------------------------------------
504 //----------------------------------------------------------------------------
505 void Path::update(double dt)
507 if( _attributes_dirty & (CMDS | COORDS) )
511 _node->getChildValues<VGubyte, int>("cmd"),
512 _node->getChildValues<VGfloat, float>("coord")
515 _attributes_dirty &= ~(CMDS | COORDS);
521 //----------------------------------------------------------------------------
522 osg::BoundingBox Path::getTransformedBounds(const osg::Matrix& m) const
524 return _path->getTransformedBounds(m);
527 //----------------------------------------------------------------------------
528 Path& Path::moveTo(float x_abs, float y_abs)
530 return addSegment(VG_MOVE_TO_ABS, x_abs, y_abs);
533 //----------------------------------------------------------------------------
534 Path& Path::move(float x_rel, float y_rel)
536 return addSegment(VG_MOVE_TO_REL, x_rel, y_rel);
539 //----------------------------------------------------------------------------
540 Path& Path::lineTo(float x_abs, float y_abs)
542 return addSegment(VG_LINE_TO_ABS, x_abs, y_abs);
545 //----------------------------------------------------------------------------
546 Path& Path::line(float x_rel, float y_rel)
548 return addSegment(VG_LINE_TO_REL, x_rel, y_rel);
551 //----------------------------------------------------------------------------
552 Path& Path::horizTo(float x_abs)
554 return addSegment(VG_HLINE_TO_ABS, x_abs);
557 //----------------------------------------------------------------------------
558 Path& Path::horiz(float x_rel)
560 return addSegment(VG_HLINE_TO_REL, x_rel);
563 //----------------------------------------------------------------------------
564 Path& Path::vertTo(float y_abs)
566 return addSegment(VG_VLINE_TO_ABS, y_abs);
569 //----------------------------------------------------------------------------
570 Path& Path::vert(float y_rel)
572 return addSegment(VG_VLINE_TO_REL, y_rel);
575 //----------------------------------------------------------------------------
578 return addSegment(VG_CLOSE_PATH);
581 //----------------------------------------------------------------------------
582 void Path::childRemoved(SGPropertyNode* child)
587 //----------------------------------------------------------------------------
588 void Path::childChanged(SGPropertyNode* child)
590 if( child->getParent() != _node )
593 if( child->getNameString() == "cmd" )
594 _attributes_dirty |= CMDS;
595 else if( child->getNameString() == "coord" )
596 _attributes_dirty |= COORDS;
599 //----------------------------------------------------------------------------
600 std::vector<float> splitAndConvert(const char del[], const std::string& str)
602 std::vector<float> values;
606 pos = str.find_first_not_of(del, pos);
607 if( pos == std::string::npos )
611 float val = strtod(&str[pos], &end);
612 if( end == &str[pos] || !end )
615 values.push_back(val);
621 } // namespace canvas
622 } // namespace simgear