# Copyright 2013, 2014 Kevin Ryde
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this file. If not, see .
# Usage: gri -output tempfile.ps dragon.gri
# gv tempfile.ps
#
# This is a recursive implementation where a dragon curve is drawn as
# two sub-dragons towards a midpoint. The sub-dragons are identical,
# just rotated. The first is from the start to the middle. The
# second is from the endpoint to the middle.
`Draw Dragon [level .level. [from .x1. .y1. to .x2. .y2.]]'
Draw a dragon curve going from .x1. .y1. to .x2. .y2. with recursion
to depth .level.
level=0 is a straight line from x1,y1 to x2,y2.
The total number of line segments for the recursion is 2^level.
The default for x1,y1 and x2,y2 is to draw horizontally from 0,0
to 1,0.
{
new .x1. .y1. .x2. .y2. .level.
.level. = \.word3.
.x1. = \.word5.
.y1. = \.word6.
.x2. = \.word8.
.y2. = \.word9.
if {rpn \.words. 3 >=} # default .level.
.level. = 8
end if
if {rpn \.words. 5 >=} # default X,Y ends
.x2. = 1
.y2. = 0
end if
if {rpn 0 .level. <=}
draw line from .x1. .y1. to .x2. .y2.
else
.level. = {rpn .level. 1 -}
# xmid,ymid is half way between x1,y1 and x2,y2 and up at
# right angle away.
#
# xmid,ymid xmid = (x1+x2 + y2-y1)/2
# ^ ^ ymid = (x1-x2 + y1+y2)/2
# / . \
# / . \
# x1,y1 ........... x2,y2
#
new .xmid. .ymid.
.xmid. = {rpn .x1. .x2. + .y2. .y1. - + 2 /}
.ymid. = {rpn .x1. .x2. - .y1. .y2. + + 2 /}
# The recursion is a level-1 dragon from x1,y1 to the midpoint
# and the same from x2,y2 to the midpoint (the latter
# effectively being a revered dragon.)
#
Draw Dragon level .level. from .x1. .y1. to .xmid. .ymid.
Draw Dragon level .level. from .x2. .y2. to .xmid. .ymid.
delete .xmid. .ymid.
end if
delete .x1. .y1. .x2. .y2. .level.
}
# Dragon curve from 0,0 to 1,0 extends out by 1/3 at the ends, so
# extents -0.5 to +1.5 for a bit of margin. The Y extent is the same
# as the width 2 to make the graph square.
set x axis -0.5 1.5 .25
set y axis -1 1 .25
draw label "start" at 0 {rpn 0 yusertocm "start" ascent 2 * - ycmtouser}
Draw Dragon level 9