input geometriesyr16;

vardef roulades(expr n,m,num,deno,total)=
  save $;
  picture $;
  pair O,A[],B[];
  path cc,poly;
  %numeric totalcen,totaltour
  O=(0,0);
  %polygone sur lequel on roule
  B1=u*(5,-5);
  %n=8;
  for k=2 upto n:
    B[k]=rotation(B1,O,(k-1)*360/n);
  endfor;
  B[n+1]=B1;
  trace B1
  for k=2 upto n:
    --B[k]
  endfor
  --cycle withcolor bleu;
  %polygone roulant
  A1=B1;
  A2=(num/deno)[B1,B2];
  for k=3 upto m:
    A[k]=rotation(A[k-2],A[k-1],(180*m-360)/m);
  endfor;
  trace A1
  for k=2 upto m:
    --A[k]
  endfor
  --cycle withcolor violet;
  %définition des centres de rotation
  pair cen[];
  cen[0]=B1;
  totalcen:=0;
  for k=0 upto n-1:
    for j=1 upto deno:
      cen[deno*k+j]:=(j/deno)[B[k+1],B[k+2]];
      totalcen:=totalcen+1;
    endfor;
  endfor;
  marque_p:="plein";
  for k=0 upto totalcen:
    pointe(cen[k]);
  endfor;
  totaltour:=num*m;
  totalcentre:=totalcen;
  for p=1 upto totaltour:
    for k=0 upto totalcen:
      cen[p*totalcen+k]=cen[k];
      totalcentre:=totalcentre+1;
    endfor;
  endfor;
  %calcul et tracé de la trajectoire
  pair I[];
  I0=A1;
  ang:=360/m;
  angn:=360/n;
  p:=0;
  path trajectoire;
  trajectoire=I0--I0;
  $=image(
    for k=num step num until total:
          %show k;
      if (k-deno*((k div deno))<num) and (k-deno*((k div deno))>0):
	if (deno*((k div deno)+1)-k)=0:
	  %message("au revoir");
	  I[p+1]=rotation(I[p],cen[deno*((k div deno)+1)],3.5*angn);
	  trace arccercle(I[p],I[p+1],cen[deno*((k div deno)+1)]) withcolor orange;
	  trajectoire:=trajectoire..arccercle(I[p],I[p+1],cen[deno*((k div deno)+1)]);
	  p:=p+1;
	else:
	  %message("bonjour");
	  I[p+1]=rotation(I[p],cen[deno*(k div deno)],angn);
	  I[p+2]=rotation(I[p+1],cen[k],ang);
	  trace arccercle(I[p],I[p+1],cen[deno*(k div deno)])--arccercle(I[p+1],I[p+2],cen[k]) withcolor orange;
	  trajectoire:=trajectoire..arccercle(I[p],I[p+1],cen[deno*(k div deno)])--arccercle(I[p+1],I[p+2],cen[k]);
	  p:=p+2;
	fi;
      elseif (k mod deno)=0:
      %message("bien joue");
      I[p+1]=rotation(I[p],cen[k],ang+angn);
      if I[p+1]<>I[p]:
	trace arccercle(I[p],I[p+1],cen[k]) withcolor orange;
	trajectoire:=trajectoire..arccercle(I[p],I[p+1],cen[k]);
      fi;
      p:=p+1;
      else:
	%message("perdu");
	I[p+1]=rotation(I[p],cen[k],ang);
	trace arccercle(I[p],I[p+1],cen[k]) withcolor orange;
	trajectoire:=trajectoire..arccercle(I[p],I[p+1],cen[k]);
	p:=p+1;
      fi;
    endfor;
    trajectoire:=trajectoire--cycle;
   );
  $
enddef;

beginfig(1);
  trace roulades(3,3,1,7,6);
endfig;

beginfig(2);
  trace roulades(3,3,1,7,7);
endfig;

beginfig(3);
  trace roulades(3,3,1,7,8);
endfig;

beginfig(4);
  trace roulades(3,3,1,7,21);
endfig;

beginfig(5);
  trace roulades(3,3,1,11,33);
  trace hachurage(trajectoire,60,0.3,0);
  fill B3--B1--B2--cycle withcolor blanc;
  trace roulades(3,3,1,11,33);
endfig;



  
end