include "..\GDIWindow\window.inc"

Sub Pause()
AscKey=0
While AscKey=0
  Events
  sleep 50
  iF WinExit=1
    WinEnd
    ExitProcess 0
  End iF
Wend
End Sub

Window "Ray2" ,640,640,2
sys_mode=4

sys x=320, y=320, c=0xffffff


'scene

ClsColor 0,0,0
int bg=0


'light
'=====

single lx,ly,lz
lx=.707
ly=.707
lz=0

int ambi=31  'light ambient / 255
int diff=224 'light diffuse / 255


function color(single li,pr,pg,pb) as sys
'========================================
sys cr,cg,cb
  if li>1 then li=1 'clamp
  if li<0 then li=0 'clamp
  cr=(diff*li+ambi)*pr
  cg=(diff*li+ambi)*pg
  cb=(diff*li+ambi)*pb
  return cb*0x10000+cg*0x100+cr 'composite
end function

function PixelAvg(sys cc,pp) as sys
'==================================
  lea esi,pp
  mov ecx,[cc]
  mov edx,[esi]
  'RED
  xor eax,eax
  mov al,cl
  add al,dl
  jnc fwd nc
  add eax,256
  .nc
  shr eax,1
  mov [esi],al
  'GREEN
  xor eax,eax
  shr ecx,8
  shr edx,8
  inc esi
  mov al,cl
  add al,dl
  jnc fwd nc
  add eax,256
  .nc
  shr eax,1
  mov [esi],al
  'BLUE
  xor eax,eax
  shr ecx,8
  shr edx,8
  inc esi
  mov al,cl
  add al,dl
  jnc fwd nc
  add eax,256
  .nc
  shr eax,1
  mov [esi],al
  return pp
end function


function sphere(sys px,py,ra,single pr,pg,pb)
'============================================
sys x,y,ri,pp,d,cc
single  r,nx,ny,nz
single li
for y=-ra to ra
for x=-ra to ra
r=hypot(x,y)
ri=r
if r<=ra
  nx=x/ra
  ny=y/ra
  nz=sqr(1-nx*nx-ny*ny) 'assume positive
  li=lx*nx+ly*ny+lz*nz
  cc=color li,pr,pg,pb
  pixel px+x,640-py-y,cc
  '
  'ANTIALIAS AVERAGING ON SPHERE EDGES
  '
  if ri=ra
    if x>=0 then d=1 else d=-1
    pp=Getpixel bHdc,px+x+d,640-py-y
    pp=PixelAvg cc,pp
    pixel px+x,640-py-y,pp
  end if
end if
next
next
end function

'objects
'=======

sphere 320,320,200,1,1,.5
sphere 300,200,150,1,.3,.5
sphere 350,200,100,1,1,1

FlipBuffer

pause
