program crossfading;

uses crush13h,crt;

type ppp= record
                r,g,b:byte;
          end;

var distance,distance1,ratio: integer;
    color1,color2,color3: integer;
    pic1,pic2,pic3: ppp;
    x,y: integer;
    c: char;

begin
     video_mode ( $13);
     initvirt;

     loadpcx ('cross1.pcx',vp[1]);
     loadpcx_nopal ('cross2.pcx',vp[2]);

     cls (0,vga);
     cls (255,vga);

     repeat
     move(mem[vp[2]:0],mem[vga:0],64000);
     move(mem[vp[1]:0],mem[vga:0],64000);
     if keypressed=true then c:=readkey;
     until c=#27;
     c:=' ';

     ratio:=70;

     repeat
           if ratio>100 then ratio:=100;
           if ratio<0 then ratio:=0;

           for x:=0 to 319 do
               for y:=0 to 199 do
                   begin
                        color1:=getpixel(x,y,vp[1]);
                        color2:=getpixel(x,y,vp[2]);

                        if color1<>color2 then
                       begin
                        getcolor (color1,pic1.r,pic1.g,pic1.b);
                        getcolor (color2,pic2.r,pic2.g,pic2.b);

                        if pic1.r=pic2.r then pic3.r:=pic1.r else
                        pic3.r:= round(pic1.r * ratio + pic2.r * (100-ratio) ) div 100;
                        if pic1.g=pic2.g then pic3.g:=pic1.g else
                        pic3.g:= round(pic1.g * ratio + pic2.g * (100-ratio) ) div 100;
                        if pic1.b=pic2.b then pic3.b:=pic1.b else
                        pic3.b:= round(pic1.b * ratio + pic2.b * (100-ratio) ) div 100;

                        distance:=20000;
                        for color3:=0 to 255 do
                            begin
                                 getcolor (color3,pic1.r,pic1.g,pic1.b);
                                 distance1:=(pic3.r-pic1.r)*(pic3.r-pic1.r) +
                                            (pic3.g-pic1.g)*(pic3.g-pic1.g) +
                                            (pic3.b-pic1.b)*(pic3.b-pic1.b);
                                 if distance1=0 then
                                    begin
                                     color1:=color3;
                                     color3:=255;
                                    end;
                                 if distance1<distance then
                                    begin
                                     distance:=distance1;
                                     color1:=color3;
                                    end;
                            end;
                       end
                        else color1:=color3;

                        putpixel (x,y,color1,vga);
                   end;

     if keypressed=true then c:=readkey;
     if c='+' then ratio:=ratio+10;
     if c='-' then ratio:=ratio-10;
     until c=#27;

     closevirt;
     video_mode ( 03);
end.