% help function for sierp3

% "sierpiter.m" written by Albert Dvornik <bert@mit.edu>
% Redistribute freely, but it would be nice to let me know if you use it.


function [] = sierpiterc(x,y,z,n,r,g,b)

%%% are we done recursing?
if (n <= 0)

%%% if we are...
  side1 = [1,2,3];
  side2 = [1,2,4];
  side3 = [1,3,4];
  side4 = [2,3,4];

%%% ...find out the "average color" for each side...
%%% (rounded to multiples of 1/32 so we don't overrun the color map)
  lr = quantize(sum(r)/4,1/32);
  lg = quantize(sum(g)/4,1/32);
  lb = quantize(sum(b)/4,1/32);
  c = [lr,lg,lb];

%%% ...and draw the 4 sides of the tetrahedron
  patch(x(side1),y(side1),z(side1),c);
  patch(x(side2),y(side2),z(side2),c);
  patch(x(side3),y(side3),z(side3),c);
  patch(x(side4),y(side4),z(side4),c);

else

%%% find the midpoints of all eight edges...
  x12 = (x(1)+x(2))/2;  y12 = (y(1)+y(2))/2;  z12 = (z(1)+z(2))/2;
  x13 = (x(1)+x(3))/2;  y13 = (y(1)+y(3))/2;  z13 = (z(1)+z(3))/2;
  x14 = (x(1)+x(4))/2;  y14 = (y(1)+y(4))/2;  z14 = (z(1)+z(4))/2;
  x23 = (x(2)+x(3))/2;  y23 = (y(2)+y(3))/2;  z23 = (z(2)+z(3))/2;
  x24 = (x(2)+x(4))/2;  y24 = (y(2)+y(4))/2;  z24 = (z(2)+z(4))/2;
  x34 = (x(3)+x(4))/2;  y34 = (y(3)+y(4))/2;  z34 = (z(3)+z(4))/2;

%%% ...interpolate the color at each midpoint...
  r12 = (r(1)+r(2))/2;  g12 = (g(1)+g(2))/2;  b12 = (b(1)+b(2))/2;
  r13 = (r(1)+r(3))/2;  g13 = (g(1)+g(3))/2;  b13 = (b(1)+b(3))/2;
  r14 = (r(1)+r(4))/2;  g14 = (g(1)+g(4))/2;  b14 = (b(1)+b(4))/2;
  r23 = (r(2)+r(3))/2;  g23 = (g(2)+g(3))/2;  b23 = (b(2)+b(3))/2;
  r24 = (r(2)+r(4))/2;  g24 = (g(2)+g(4))/2;  b24 = (b(2)+b(4))/2;
  r34 = (r(3)+r(4))/2;  g34 = (g(3)+g(4))/2;  b34 = (b(3)+b(4))/2;

%%% ...and recurse
  sierpiterc([x(1),x12,x13,x14],[y(1),y12,y13,y14],[z(1),z12,z13,z14],n-1, ...
             [r(1),r12,r13,r14],[g(1),g12,g13,g14],[b(1),b12,b13,b14]);
  sierpiterc([x12,x(2),x23,x24],[y12,y(2),y23,y24],[z12,z(2),z23,z24],n-1, ...
             [r12,r(2),r23,r24],[g12,g(2),g23,g24],[b12,b(2),b23,b24]);
  sierpiterc([x13,x23,x(3),x34],[y13,y23,y(3),y34],[z13,z23,z(3),z34],n-1, ...
             [r13,r23,r(3),r34],[g13,g23,g(3),g34],[b13,b23,b(3),b34]);
  sierpiterc([x14,x24,x34,x(4)],[y14,y24,y34,y(4)],[z14,z24,z34,z(4)],n-1, ...
             [r14,r24,r34,r(4)],[g14,g24,g34,g(4)],[b14,b24,b34,b(4)]);
end


