% lgc2refractionEdited.mp
% lgc means LaTeX Graphics Companion
% 2013

prologues := 1;

vardef lensrefractray(expr s,a,p,q,rir)=
  save tI,tn,ia,ib,I,J,K,sib;
  pair I,J,K;
  tI = xpart(p intersectiontimes (s--(s+30cm*dir(a))));
  if tI>=0:
    I=point tI of p;
    draw s--I;
    tn=angle(direction tI of p)+90;
    ia=tn-angle(s-I);
    sib=sind(ia)/rir;
    ib=-angle(1+-+sib,sib);    
    J=I+dir(tn+180+ib)*2cm;
    tI := xpart(q intersectiontimes (I--J));
    if tI>=0:
      K:=point tI of q;
      draw I--K withcolor blue;
      tn:=angle(direction tI of q)+90;
      ia:=tn-angle(I-K);
      sib:=rir*sind(ia);
      ib:=angle(1+-+sib,sib);    
      J:=K+dir(tn+ib)*2cm;
      draw K--J;
    fi;
  fi;
enddef;

vardef refractray(expr s,a,p,rir)=
  save tI,tn,ia,ib,I,J,sib;
  pair I,J;
  tI = xpart(p intersectiontimes (s--(s+30cm*dir(a))));
  if tI>=0:
    I=point tI of p;
    draw s--I;
    tn=angle(direction tI of p)+90;
    ia=tn-angle(s-I);
    sib=sind(ia)/rir;
    ib=-angle(1+-+sib,sib);
    J=I+dir(tn+180+ib)*2cm;
    draw I--J withcolor blue;
  fi;
enddef;

vardef reflectray(expr s,a,p)=
  save tI,tn,ia,I,J;
  pair I,J;
  tI=xpart(p intersectiontimes (s--(s+30cm*dir(a))));
  if tI>=0:
    I=point tI of p;
    draw s--I;
    tn=angle(direction tI of p)+90;
    ia=tn-angle(s-I);
    J=I+dir(tn+ia)*2cm;
    draw I--J withcolor blue;
  fi;
enddef;

beginfig(2);
  numeric u;
  u=3mm;
  path p;
  p=((5u,-6u)..(4u,-2u)..(4.5u,0)..(5u,5u)) rotated 90;
  for a=40 step 5 until 140: reflectray(origin,a,p); endfor;
  draw p withcolor red;
endfig;

beginfig(1);
  for a=40 step 5 until 140: refractray(origin,a,p,1.5); endfor;
  draw p withcolor red;
endfig;

beginfig(3);
  path q;
  q = reverse (p yscaled (-1)) shifted (up*10.5u);
  fill (p--q--cycle) withcolor red;
  for a=46 step 3 until 120:
    lensrefractray(origin,a,p,q,1.4);
  endfor;
endfig;

end.