function menger(level,lit) % Fractal cube, the Menger sponge. % menger(level) generates 20^level cubes. % menger(level,true) is illuminated. % menger(level,false) is not illuminated, so it is faster. if nargin < 1, level = 3; end if nargin < 2, lit = true; end V = [-3 -3 -3; -3 -3 3; -3 3 -3; -3 3 3; 3 -3 -3; 3 -3 3; 3 3 -3; 3 3 3]; init_fig(lit) sponge(V,level,lit) % -------------------------------------------------------- function sponge(v,level,lit) if level > 0 v = v/3; for x = [-2 0 2] for y = [-2 0 2] for z = [-2 0 2] if nnz([x y z]) > 1 sponge(v+[x y z],level-1,lit) end end end end else cube(v,lit) end end function cube(v,lit) f = [ 1 5 7 3 3 7 8 4 1 3 4 2 2 4 8 6 1 2 6 5 5 6 8 7]; gold = [1 .85 .60]; p = patch(Vertices = v, ... Faces = f, ... FaceColor = gold, ... LineWidth = 0.5); if lit golden = [0.7,0.5,0.3,1.0,0.2]; material(p,golden) end end function init_fig(lit) axis(4*[-1 1 -1 1 -1 1]) axis equal off vis3d rotate3d on view(60,15) if lit camlight(-45,10); % set(gcf,'windowbuttonmotionfcn',@wbmf); end end function wbmf(~,~) a = gca; l = findobj(a,'type','light'); camlight(l,-45,10); end end