/*
 * globe.PRG by DOM COOK
 * (c) 2019 Sollia 3
 */



PROGRAM Aglobe;
global
tex[2];
canvas;
i;j;
latitude;
longitude;
light;
file0;
dr_id;

wt;  wt2;
ht;  ht2;
wc;  wc2;
hc;  hc2;


x0;
BEGIN
set_mode(m800x600);
set_fps(60,0);
file0 = load_fpg("globe.fpg");
tex =1;
tex[1] =1;
tex[2] =2;
wt= graphic_info(file0,tex,g_wide);
ht= graphic_info(file0,tex,g_height);
wc= wt/2;
wc2=wc/2;
x0 =wt/2;
hc =ht;

hc2=hc/2;

canvas = new_map(wc,hc,wc2,hc2,0);

graph = tex;
globe();

redraw_globe();
   frame;

dr_id =draw(1,15,15,0,x+x0,y,x+x0,y+ht);
write_int(0,10,590,0,&fps);

write(0,100,200,0,"The texture for the globe is being read from here");
write(0,100,220,0,"Select the texture with keys _1 and _2");


write(0,100,580,0,"Use LEFT / RIGHT arrow keys to rotate the globe");
loop

    if(key(_right))
        x0+=wt-4;
     end
    if(key(_left))
        x0+=4;
     end
    if(key(_1))
        tex = tex[1];
     end
    if(key(_2))
        tex = tex[2];
     end
graph = tex;


   if(key(_left) or key(_right) or key(_1) or key(_2))
        x0%=wt;
        move_draw(dr_id,15,15,x+x0,y,x+x0,y+ht);
        redraw_globe();
    end



  if(key(_esc)) exit(0,0); end
frame;
//    delete_draw(dr_id);
end

END

process globe()

begin
x = 600;
y =300;
graph = canvas;
loop

frame;

end

end


function redraw_globe();
begin
for(i =0; i<wc2; i+=1)
for(j =0; j<hc; j+=1)
   latitude =  asin((hc2-j)*2000/wc);
   longitude =  acos((wc2-i)*2000/wc);
   light = 7-get_distx(longitude,7);
   map_put_pixel(file0,canvas,wc2+get_distx(latitude,i),j,
    map_get_pixel(file0,tex,(x0+i)%wt,j)+light);
   map_put_pixel(file0,canvas,wc2-get_distx(latitude,i),j,
    map_get_pixel(file0,tex,((x0-i)+wt)%wt,j)-light);

end
end

end
