/*
 * 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
y =400;
x = 400;
graph = canvas;
size=100;
loop

frame;

end

end


function redraw_globe();
private
l; ct;
r; cc;
tpx,tpy;
cpx,cpy;
px;
h;
begin
h =wc/2;
r=wc*1000/3142;
l=90;
ct= x0;
cc =wc/2;
for(i =-l; i<l; i+=1)
      longitude = i*90000/l;
    tpx =ct+i;
    tpx = (tpx+360)%360;

    for(j =-h; j<h; j+=1)
        latitude =  -j*90000/h;

    tpy = h+j;
    cpy = cc+get_disty(latitude,r);
    cpx =get_disty(longitude,-r);
    cpx= cpx*get_distx(latitude,1000)/1000;
    cpx+=cc;
   light = longitude*7/90000;
   //light =0;

   px =map_get_pixel(file,tex,tpx,tpy)+light;
   map_put_pixel(file0,canvas,cpx,cpy,px);
end
end

end
