#! /usr/bin/python3
# Last edited on 2020-12-23 20:10:21 by jstolfi

import sys

def func1(WP,WN,VN,VB,VP):
  return VB + (VP-VB)*((WP*WP + WN*WN)/10000)

def main():
  n = 50  # Size of plot grid
  func = func1
  Wmax = 100
  VN = -80;
  VB = -60;
  VP = -30;
  write_preamble(Wmax,VN,VB,VP)
  for ix in range(n):
    for iy in range(n):
      plot_square(ix,iy,n,Wmax,VN,VB,VP,func)
  write_postamble()


def write_preamble(Wmax,VN,VB,VP):
  sys.stdout.write("background{ color rgb < 1, 1, 1 > }\n")
  sys.stdout.write("#declare tx_vidro =\n")
  sys.stdout.write("  texture{\n")
  sys.stdout.write("    pigment{ color rgb <1, 1, 1> transmit 0.900 } \n")
  sys.stdout.write("    finish{ diffuse 0.050 ambient 0.030 reflection 0.020 } \n")
  sys.stdout.write("  }\n")
  sys.stdout.write("#declare Wmax = %.4f;\n" % Wmax)
  sys.stdout.write("#declare VN = %.4f;\n" % VN)
  sys.stdout.write("#declare VB = %.4f;\n" % VB)
  sys.stdout.write("#declare VP = %.4f;\n" % VP)
  sys.stdout.write("\n")
  sys.stdout.write("#declare caixa =\n")
  sys.stdout.write("  box{ < 0, 0, VN >, < Wmax, Wmax, VP > texture{ tx_vidro } }\n")
  sys.stdout.write("\n")
  sys.stdout.write("#declare surf =\n")
  sys.stdout.write("  union{\n")


def plot_square(ix,iy,n,Wmax,VN,VB,VP,func):
  plot_triangle(ix,iy,n,Wmax,VN,VB,VP,func, 0,0, 1,0)
  plot_triangle(ix,iy,n,Wmax,VN,VB,VP,func, 1,0, 1,1)
  plot_triangle(ix,iy,n,Wmax,VN,VB,VP,func, 1,1, 0,1)
  plot_triangle(ix,iy,n,Wmax,VN,VB,VP,func, 0,1, 0,0)


def plot_triangle(ix,iy,n,Wmax,VN,VB,VP,func, dxa,dya, dxb,dyb):
  sys.stdout.write("    triangle{")

  xa = Wmax*(ix+dxa)/n; ya = Wmax*(iy+dya)/n; za = func(xa,ya,VN,VB,VP);
  sys.stdout.write(" < %.2f, %.2f, %.2f >," % (xa, ya, za))

  xb = Wmax*(ix+dxb)/n; yb = Wmax*(iy+dyb)/n; zb = func(xb,yb,VN,VB,VP);
  sys.stdout.write(" < %.2f, %.2f, %.2f >," % (xb, yb, zb))

  xc = Wmax*(ix+0.5)/n; yc = Wmax*(iy+0.5)/n; zc = func(xc,yc,VN,VB,VP);
  sys.stdout.write(" < %.2f, %.2f, %.2f >" % (xc, yc, zc))

  sys.stdout.write(" }\n" )

def write_postamble():
  sys.stdout.write \
    ( 
    """
      texture{ pigment{ color rgb < 1.000, 0.980, 0.500 > } finish{ diffuse 0.9 ambient 0.1 } }
    }
    
    #include "eixos.inc"
    
    object{ eixos(1.25*Wmax) translate VB*z }
    object{ surf }
    object{ caixa }
    
    #include "camlight.inc"
    #declare centro_cena = < Wmax/2, Wmax/2, VB >;
    #declare raio_cena = 1.7*Wmax;
    #declare dir_camera = < 10.00, 1.00, 4.00 >;
    #declare dist_camera = 5*raio_cena;
    camlight(centro_cena, raio_cena, dir_camera, dist_camera, z, 1.20)
    """
    )
  sys.stdout.flush()

main()
