[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Vanishing MrEd




Answers in stages: Part 1. 

I re-wrote the program a bit, to understand what it was doing. I am running
inside of MrEd (Debug) and it runs just fine. Were you trying to print
these things? 

  Welcome to DrScheme, version 103d104.
  Language: Graphical Full Scheme (MrEd) Custom.
  > (test 1)
  4
  > (test 2)
  16
  > (test 3)
  64
  > (test 7)
  16384
  > (test 8)
  65536
  > 

;; -----------------------------------------------------------------------------

(define-struct vertex (x y z))
;; Vertex == (make-vertex Num Num Num)

;; Triangle = (list Vertex Vertex Vertex)

; new-vertex : Num Num -> Vertex 
; make a new vertex by bisecting an edge and calculating a random height.
(define (new-vertex v0 v1)
  (let ([x0 (vertex-x v0)]
        [y0 (vertex-y v0)]
        [z0 (vertex-z v0)]
        [x1 (vertex-x v1)]
        [y1 (vertex-y v1)]
        [z1 (vertex-z v1)])
    (make-vertex
     (/ (+ x0 x1) 2)
     (/ (+ y0 y1) 2)
     (+ (/ (+ z0 z1) 2) (random-offset v0 v1)))))

; random-offset : Vertex Vertex -> Num
; how to calculate the random height.
(define (random-offset v0 v1)
  (* (distance v0 v1) (- 1 (exact->inexact (/ (random 200000) 100000)))))

; distance : Vertex Vertex -> Num 
(define (distance v0 v1)
  (let ([x0 (vertex-x v0)]
        [y0 (vertex-y v0)]
        [z0 (vertex-z v0)]
        [x1 (vertex-x v1)]
        [y1 (vertex-y v1)]
        [z1 (vertex-z v1)])
    (sqrt (+ (expt (- x1 x0) 2) (expt (- y1 y0) 2) (expt (- z1 z0) 2)))))

; calculate-new-triangles : Vertex Vertex Vertex -> (list Triangle Triangle Triangle Triangle)
; take a triangle and make four new ones by connecting the midpoints of edges.
(define (calculate-new-triangles a b c)
  (let ([d (new-vertex a b)]
        [e (new-vertex b c)]
        (f (new-vertex c a)))
    `((,a ,d ,f) (,d ,b ,e) (,e ,c ,f) (,d ,e ,f))))

; new-triangles : (listof Triangle) -> (listof (list Triangle Triangle Triangle Triangle))
; take a list of triangles and make four new triangles for each original triangle.
(define (new-triangles triangles)
  (if (null? triangles) 
      '()
      (append
       (calculate-new-triangles (caar triangles) (cadar triangles) (caddar triangles))
       (new-triangles (cdr triangles)))))

; gen-terrain : (listof Triangle) N -> (listof Triangles)
; generate terrain by starting with a single equilateral triangle and generating new triangles
; for several (small integer) iterations.
(define (gen-terrain triangles iterations)
  (if (= iterations 0) 
      triangles
      (gen-terrain (new-triangles triangles) (- iterations 1))))

; equilateral-triangle : Triangle 
(define equilateral-triangle
  (list (make-vertex 0 0 0)
        (make-vertex 1 0 0)
        (make-vertex 0.5 (/ (sqrt 3) 2) 0)))

;; test : N -> Bool
;; generate 2^(* 2 n) triangles
(define (test n)
  (length (gen-terrain (list equilateral-triangle) n)))