Skip to content

Commit 1ce2793

Browse files
committed
make star() ~15x faster using opengl commands instead of BezierPath.
1 parent 9ef982d commit 1ce2793

File tree

1 file changed

+36
-12
lines changed

1 file changed

+36
-12
lines changed

nodebox/graphics/context.py

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -685,18 +685,42 @@ def star(x, y, points=20, outer=100, inner=50, **kwargs):
685685
""" Draws a star with the given points, outer radius and inner radius.
686686
The current stroke, strokewidth and fill color are applied.
687687
"""
688-
# GL_POLYGON only works with convex polygons,
689-
# so we use a BezierPath (which does tessellation for fill colors).
690-
p = BezierPath(**kwargs)
691-
p.moveto(x, y+outer)
692-
for i in range(0, int(2*points)+1):
693-
r = (outer, inner)[i%2]
694-
a = pi*i/points
695-
p.lineto(x+r*sin(a), y+r*cos(a))
696-
p.closepath()
697-
if kwargs.get("draw", True):
698-
p.draw(**kwargs)
699-
return p
688+
radii = [outer, inner] * int(points+1); radii.pop() # which radius?
689+
f = pi / points
690+
v = [(x+r*sin(i*f), y+r*cos(i*f)) for i, r in enumerate(radii)]
691+
692+
if kwargs.get("draw", True):
693+
fill, stroke, strokewidth, strokestyle = color_mixin(**kwargs)
694+
695+
if fill is not None:
696+
glColor4f(fill[0], fill[1], fill[2], fill[3] * _alpha)
697+
698+
glBegin(GL_TRIANGLE_FAN)
699+
glVertex2f(x, y)
700+
for (vx, vy) in v:
701+
glVertex2f(vx, vy)
702+
glEnd()
703+
704+
if stroke is not None and 0 < strokewidth:
705+
glLineWidth(strokewidth)
706+
if strokestyle != _strokestyle:
707+
glLineDash(strokestyle)
708+
glColor4f(stroke[0], stroke[1], stroke[2], stroke[3] * _alpha)
709+
710+
glBegin(GL_LINE_LOOP)
711+
for (vx, vy) in v:
712+
glVertex2f(vx, vy)
713+
glEnd()
714+
else:
715+
# For whatever reason, the original api specified that you
716+
# can get the path to the star. This is about 20x slower,
717+
# but I'm keeping it here for backwards compatibility.
718+
p = BezierPath(**kwargs)
719+
p.moveto(x, y+outer)
720+
for (vx, vy) in v:
721+
p.lineto(vx, vy)
722+
p.closepath()
723+
return p
700724

701725
#=====================================================================================================
702726

0 commit comments

Comments
 (0)