(use gl glut 3viewer typed-records matchable)

(define red    '#f32(1 0 0 1))   ;;      
(define blue   '#f32(0 0 1 1))	  ;;	  
(define green  '#f32(0 1 0 1))	  ;;	  
(define yellow '#f32(1 1 0 1))	  ;;	  
(define white  '#f32(1 1 1 1))	  ;;	  
(define orange '#f32(1 0.5 0 1)) ;; 	  
(define black  '#f32(0 0 0 1)) ;;	 

(define colors
  `((1 . ,red    ) ;;  red    
    (2 . ,blue   ) ;;	 blue   
    (3 . ,green  ) ;;	 green  
    (4 . ,yellow ) ;;	 yellow 
    (5 . ,white  ) ;;	 white  
    (6 . ,orange ) ;; 	 orange 
    (7 . ,black  ) ;;	 black
    ))

(define (get c)
  (alist-ref c colors))

(defstruct cspec
  (x 0)
  (y 0)
  (z 0)
  (n (get 1))   ;; north
  (s (get 1))   ;; south
  (e (get 1))   ;; east
  (w (get 1))   ;; west
  (t (get 1))   ;; top
  (b (get 1)))  ;; bottom

(define a 0)

(define (spin id)
  (set! a (modulo (+ a 1) 360)))

(define (colorize id col)
  (gl:Materialfv 
   gl:FRONT_AND_BACK gl:AMBIENT_AND_DIFFUSE
   (if (object-highlighted? id)
       '#f32(1 1 0 1)
       col)))

(define (make-cuber cspec)
  (lambda (id)
    (gl:Translatef (cspec-x cspec)(cspec-y cspec)(cspec-z cspec))
    (draw-side id (cspec-w cspec)) ;; west side
    (gl:Translatef 0 1 0)
    (gl:Rotatef 90 1 0 0)
    (draw-side id (cspec-e cspec)) ;; east side
    (gl:Translatef 0 0 1)
    (gl:Rotatef 90 0 1 0)
    (draw-side id (cspec-n cspec)) ;; east side
    (gl:Translatef 0 0 1)
    (gl:Rotatef 90 0 1 0)
    (draw-side id (cspec-s cspec)) ;; east side
    (gl:Translatef 0 0 1)
    (gl:Rotatef 90 0 1 0)
    (draw-side id (cspec-t cspec)) ;; east side
    (gl:Translatef 0 1 0)
    (gl:Rotatef 90 1 0 0)
    (draw-side id (cspec-b cspec)) ;; east side
       ))
    
(define (draw-side id color)
  (colorize id color) ;; '#f32(1 0 0 1))
  (gl:Begin gl:POLYGON)
  (gl:Vertex2f 0 0) 
  (gl:Vertex2f 0 1) 
  (gl:Vertex2f 1 1) 
  (gl:Vertex2f 1 0) 
  (gl:End) 
  )

(define data
  (map (lambda (inl)
	 (map string->number (string-split inl)))
       (with-input-from-file "data.scm"
	 read-lines)))

(print "data: " data)

(use trace)

;; (add-object draw-cube animate: spin select: (lambda _ (print "oink!")))
;; (add-object draw-polygon animate: spin select: (lambda _ (print "oink!")))
(gl:Clear gl:COLOR_BUFFER_BIT)
(for-each
 (lambda (dat)
   ;; (let ((c1 (make-cspec e: red w: blue n: green s: yellow t: white b: orange)))
   (match dat
     ((x y z n s e w t b)
      (let ((c1 (make-cspec x: x y: y z: z n: (get n) s: (get s) e: (get e) w: (get w) t: (get t) b: (get b))))
	(pp (cspec->alist c1))
	(add-object (make-cuber c1) select: (lambda _ (print "oink!")))))
     (else (print "bad object " dat))))
 data)
(gl:Flush)      
(start-viewer)
