%
%	vonkoch.t
%
%	routines that implement geometric replacement schemes
%
%	Return point that is the fraction t between P and Q.
%	"Lirp" stands for linear interpolation.

function Lirp(P,Q: realpoint, t: real): realpoint
	var newpt: realpoint

	newpt.x := P.x + t*(Q.x-P.x)
	newpt.y := P.y + t*(Q.y-P.y)
	result(newpt)
end Lirp


function ConvertToScreen(p: realpoint): intpoint
	var q: intpoint
	q.x := round(p.x*scale) + xoffset
	q.y := Yres - round(p.y*scale) + yoffset
	result(q)
end ConvertToScreen


%	Rotate P about Q through angle ang.

function Rotate(P, Q: realpoint, ang: real): realpoint
	var s,c,x,y: real
	var pt: realpoint

	s := sin(ang)
	c := cos(ang)
	x := P.x-Q.x;
	y := P.y-Q.y;
	pt.x :=  c*x - s*y + Q.x
	pt.y :=  s*x + c*y + Q.y
	result(pt)
end Rotate


procedure DrawFractal(pts: fractal, n: int)
	var p0,p1: intpoint

	cls
	for i: 1..n-1
		p0 := ConvertToScreen(pts(i))
		p1 := ConvertToScreen(pts(i+1))
		drawline(p0.x, p0.y, p1.x, p1.y, 1)
	end for
end DrawFractal


procedure PutFractal(pts: fractal, n: int)
	var p0,p1: intpoint

	for i: 1..n
		p0 := ConvertToScreen(pts(i))
		put "(", pts(i).x, ",", pts(i).y, "), [", p0.x, ",", p0.y, "]"
	end for
end PutFractal

%
%	Replace the sequence of line segments in current, putting the
%	result in new using the replacement rule called rule.
%
procedure Replace(current: fractal, n: int,
		  var next: fractal, var nnext: int,
		  function rule(p0,p1: realpoint, var n: int): fractal)

	var newfractal: fractal
	var nfrac: int
	nnext := 0
	for i: 1..n-1
		newfractal := rule(current(i), current(i+1), nfrac)
		% Append newfractal to next
		for j: 1..nfrac
			nnext := nnext + 1
			next(nnext) := newfractal(j)
		end for
	end for
end Replace



%	Replacement rule for von Koch curve.

function RepVonKoch(P,Q: realpoint, var n: int): fractal
	var P1, Q1, C: realpoint
	var newfractal: fractal

	newfractal(1) := P
	newfractal(2) := Lirp(P,Q,1/3)
	newfractal(4) := Lirp(P,Q,2/3)
	newfractal(3) := Rotate(newfractal(2),newfractal(4),Pi/3)
	newfractal(5) := Q
	n := 5
	result(newfractal)
end RepVonKoch




