--Copyright The Numerical Algorithms Group Limited 1994.
-- Sierpinsky's Tetrahedron

-- Bring DH matrices into the environment
)set expose add con DenavitHartenbergMatrix

)read dhtri

-- set up the coordinates of the corners of a tetrahedron
x1:DoubleFloat := sqrt(2.0@DoubleFloat/3.0@DoubleFloat)
x2:DoubleFloat := sqrt(3.0@DoubleFloat)/6

p1 := point [-0.5@DoubleFloat, -x2, 0.0@DoubleFloat]
p2 := point [0.5@DoubleFloat, -x2, 0.0@DoubleFloat]
p3 := point [0.0@DoubleFloat, 2*x2, 0.0@DoubleFloat]
p4 := point [0.0@DoubleFloat, 0.0@DoubleFloat, x1]

-- The base of the tetrahedron
baseTriangle  := [p2, p1, p3]

-- The "middle triangle" inscribed in the base of the tetrahedon
mt  := [0.5@DoubleFloat*(p2+p1), 0.5@DoubleFloat*(p1+p3), 0.5@DoubleFloat*(p3+p2)]

-- The bases of the triangles of the subdivided tetrahedon
bt1 := [mt.1, p1, mt.2]
bt2 := [p2, mt.1, mt.3]
bt3 := [mt.2, p3, mt.3]
bt4 := [0.5@DoubleFloat*(p2+p4), 0.5@DoubleFloat*(p1+p4), 0.5@DoubleFloat*(p3+p4)]

-- create the transformations which bring the base of the tetrahedron
-- to the bases of the subdivided tetrahedron
tt1 := tri2tri(baseTriangle, bt1)
tt2 := tri2tri(baseTriangle, bt2)
tt3 := tri2tri(baseTriangle, bt3)
tt4 := tri2tri(baseTriangle, bt4)

-- Draw a Sierpinsky tetrahedron with n levels of recursive subdivision
drawPyramid(n) ==
  s := create3Space()$ThreeSpace DoubleFloat
  dh := rotatex(0.0@DoubleFloat)
  drawPyramidInner(s, n, dh)
  makeViewport3D(s, "Sierpinsky Tetrahedron")$VIEW3D

-- Recursively draw a Sierpinsky tetrahedron
drawPyramidInner(s, n, dh) ==
  n = 0 => makeTetrahedron(s, dh, n)
  -- draw the 4 recursive pyramids
  drawPyramidInner(s, n-1, dh * tt1)
  drawPyramidInner(s, n-1, dh * tt2)
  drawPyramidInner(s, n-1, dh * tt3)
  drawPyramidInner(s, n-1, dh * tt4)

-- draw a tetrahedron into the given space, with the given color,
-- transforming it by the given DH matrix
makeTetrahedron(sp, dh, color) ==
  w1 := dh*p1
  w2 := dh*p2
  w3 := dh*p3
  w4 := dh*p4
  polygon(sp, [w1, w2, w4])
  polygon(sp, [w1, w3, w4])
  polygon(sp, [w2, w3, w4])
  void()
