Home My Page Projects Code Snippets Project Openings 3D graphics for Standard ML
Summary Activity SCM

SCM Repository

[sml3d] Diff of /trunk/sml3d/src/particles/compiler/translate.sml
ViewVC logotype

Diff of /trunk/sml3d/src/particles/compiler/translate.sml

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1008, Sun Jan 16 17:04:08 2011 UTC revision 1152, Sun May 8 08:55:38 2011 UTC
# Line 1  Line 1 
1  (* translate.sml  (* translate.sml
2   *  
3   * COPYRIGHT (c) 2009 John Reppy (http://cs.uchicago.edu/~jhr)   * COPYRIGHT (c) 2009 John Reppy (http://cs.uchicago.edu/~jhr)
4   * All rights reserved.   * All rights reserved.
5   *   *
# Line 8  Line 8 
8    
9  structure Translate : sig  structure Translate : sig
10    
11      val compile : Particles.particle_group -> PSysIR.program      val compile : Particles.program -> PSysIR.program
12    
13    end = struct    end = struct
14    
# Line 20  Line 20 
20    
21      fun printErr s = TextIO.output(TextIO.stdErr, s ^ "\n")      fun printErr s = TextIO.output(TextIO.stdErr, s ^ "\n")
22    
     datatype particle_state = PS of {  
         pos : IR.var,           (* vec3 *)  
         vel : IR.var,           (* vec3 *)  
         size : IR.var,          (* float *)  
         ttl : IR.var,           (* float *)  
         color : IR.var,         (* vec3 (NOTE: should be vector4) *)  
         pos2 : IR.var,          (* vec3 *)  
         dummy : IR.var  
       }  
   
23    (* special PSV global variables *)    (* special PSV global variables *)
24      val epsilon = PSV.constf(0.00001)      val epsilon = PSV.constf(0.00001)
25    
26    (* constants *)    (* constants *)
27      val pi = 3.14159265358979      val pi = 3.14159265358979
28    
29    (* dummy placeholder *)    (* translation environment *)
30      fun dummy (state, k) =      datatype ir_env = TE of (IR.block list ref * IR.var PSV.Map.map * IR.var PSV.SVMap.map)
31            IR.mkPRIM(      fun insertVar (TE(blks, v_env, sv_env), x, x') = TE(blks, PSV.Map.insert (v_env, x, x'), sv_env)
32              IR.newLocal(      fun insertSVar (TE(blks, v_env, sv_env), x, x') = (case (PSV.SVMap.find (sv_env, x))
33                "temp",          of NONE => raise Fail("Changing mapping to state var that doesn't exist.")
34                IR.T_BOOL,           | SOME var => (
35                (IR.COPY, [IR.newConst("c", IR.C_BOOL false)])             IR.setRenderVar(x', IR.isRenderVar var);
36              ),             TE(blks, v_env, PSV.SVMap.insert (sv_env, x, x'))
             IR.COPY,  
             [IR.newConst("c", IR.C_BOOL false)],  
             k state  
           )  
   
   
     fun retState s = let  
       val PS{pos, vel, size, ttl, color, pos2, dummy} = s  
      in  
       IR.mkRETURN (  
         [pos, vel, size, ttl, color, pos2, dummy],  
         [IR.POS, IR.VEL, IR.SZ, IR.TTL, IR.COLOR, IR.POS2, IR.DUMMY]  
37        )        )
38       end        (* end case *))
39    
40    (* translation environment *)      fun retState (TE(_, _, sv_env)) = IR.mkRETURN (PSV.SVMap.listItems sv_env)
     datatype env = TE of (IR.block list ref * IR.var PSV.Map.map)  
41    
42      fun psvToIRVar (TE(_, env), x as PSV.V{name, id, ...}) = (case PSV.Map.find(env, x)    (* Interaction with environment and psys variables *)
43        fun psvToIRVar (TE(_, env, _), x as PSV.V{name, id, ...}) = (case PSV.Map.find(env, x)
44             of SOME x' => x'             of SOME x' => x'
45              | NONE => raise Fail (String.concat["unknown variable ", name, " with ID ", Int.toString id])              | NONE => raise Fail (String.concat["unknown variable ", name, " with ID ", Int.toString id])
46            (* end case *))            (* end case *))
47    
48      fun insert (TE(blks, env), x, x') = TE(blks, PSV.Map.insert (env, x, x'))      fun pssvToIRVar (TE(_, _, env), x as PSV.SV{name, id, ...}) = (case PSV.SVMap.find(env, x)
49               of SOME x' => x'
50                | NONE => raise Fail (String.concat["unknown state variable ", name, " with ID ", Int.toString id])
51                (* end case *))
52    
53    (* create a block that implements the given continuation *)    (* create a block that implements the given continuation *)
54      fun newBlock (TE(blks, _), k : particle_state -> IR.stmt) = let      fun newBlockWithArgs (env as TE(blks, _, sv_env), args, k : ir_env -> IR.stmt) = let
55            val pos = IR.newParam ("ps_pos", IR.T_VEC)         fun copyVar(v as IR.V{name, varType, ...}) = IR.newParam(name, varType)
56            val vel = IR.newParam ("ps_vel", IR.T_VEC)         val newState = List.map copyVar (PSV.SVMap.listItems sv_env)
57            val size = IR.newParam ("ps_size", IR.T_FLOAT)         fun inssv((oldv, newv), TE(theBlks, v_env, svenv)) = let
58            val ttl = IR.newParam ("ps_ttl", IR.T_FLOAT)           val theKey =
59            val color = IR.newParam ("ps_color", IR.T_VEC)             List.find
60            val dummy = IR.newParam ("ps_dummy", IR.T_FLOAT)              (fn v => IR.varEq(PSV.SVMap.lookup(svenv, v), oldv))
61            val pos2 = IR.newParam ("ps_pos2", IR.T_VEC)              (PSV.SVMap.listKeys svenv)
62            val state = PS{pos=pos, vel=vel, size=size, ttl=ttl, color=color, pos2=pos2, dummy=dummy}           val sv = (case theKey
63            val blk = IR.newBlock ([pos, vel, size, ttl, color, pos2, dummy], k state)             of SOME x => x
64                | NONE => raise Fail("Trying to create new mapping for variable that doesn't already exist.")
65             (* end case *))
66            in            in
67              blks := blk :: !blks;           IR.setRenderVar(newv, IR.isRenderVar oldv);
68              blk           TE(theBlks, v_env, PSV.SVMap.insert(svenv, sv, newv))
69            end            end
70    
71          fun newBlockWithArgs (TE(blks, _), args, k : particle_state -> IR.stmt) = let             val blk = IR.newBlock (
72            val pos = IR.newParam ("ps_pos", IR.T_VEC)                 newState @ args,
73            val vel = IR.newParam ("ps_vel", IR.T_VEC)                 k (List.foldl inssv env
74            val size = IR.newParam ("ps_size", IR.T_FLOAT)                     (ListPair.zipEq
75            val ttl = IR.newParam ("ps_ttl", IR.T_FLOAT)                         (PSV.SVMap.listItems sv_env, newState)
76            val color = IR.newParam ("ps_color", IR.T_VEC)                     )
77            val dummy = IR.newParam ("ps_dummy", IR.T_FLOAT)                 )
78            val pos2 = IR.newParam ("ps_pos2", IR.T_VEC)              )
           val state = PS{pos=pos, vel=vel, size=size, ttl=ttl, color=color, pos2=pos2, dummy = dummy}  
           val blk = IR.newBlock ([pos, vel, size, ttl, color, pos2, dummy] @ args, k state)  
79            in            in
80              blks := blk :: !blks;              blks := blk :: !blks;
81              blk              blk
82            end            end
83    
84      fun goto (PS{pos, vel, size, ttl, color, pos2, dummy}, blk) =          fun newBlock (env, k) = newBlockWithArgs(env, [], k)
           IR.mkGOTO(blk, [pos, vel, size, ttl, color, pos2, dummy])  
   
         fun gotoWithArgs(PS{pos, vel, size, ttl, color, pos2, dummy}, args, blk) =  
           IR.mkGOTO(blk, [pos, vel, size, ttl, color, pos2, dummy] @ args)  
85    
86      fun letPRIM (x, ty, p, args, body) = let      fun letPRIM (x, ty, p, args, body) = let
87            val x' = IR.newLocal(x, ty, (p, args))            val x' = IR.newLocal(x, ty, (p, args))
# Line 112  Line 89 
89              IR.mkPRIM(x', p, args, body x')              IR.mkPRIM(x', p, args, body x')
90            end            end
91    
92    (* prim bound to state variable (S_LOCAL for now) *)     fun gotoWithArgs(TE(_, _, env), args, blk) = let
93      fun letSPRIM(x, ty, p, args, body) = let  
94            val x' = IR.new(x, IR.S_LOCAL(ref (p, args)), ty)       fun copyVar(v as IR.V{name, varType, ...}) = IR.newLocal(name^"_copy", varType, (IR.RAND, []))
95    
96         fun copyRenderVar (oldv, newv) = IR.setRenderVar (newv, IR.isRenderVar oldv)
97    
98         val vars = ((PSV.SVMap.listItems env) @ args)
99         val varCopies = List.map copyVar vars
100    
101         fun mkCopy(newv, oldv, k) = IR.mkPRIM(newv, IR.COPY, [oldv], k)
102            in            in
103              IR.mkPRIM(x', p, args, body x')       List.app copyRenderVar (ListPair.zipEq (vars, varCopies));
104         ListPair.foldr mkCopy (IR.mkGOTO(blk, varCopies)) (varCopies, vars)
105            end            end
106    
107       fun goto (env, blk) = gotoWithArgs(env, [], blk)
108    
109    
110    (* Not sure if this should be made into a primitive or not, but    (* Not sure if this should be made into a primitive or not, but
111     * basically this creates the XOR'd value of var1 and var2 and     * basically this creates the XOR'd value of var1 and var2 and
112     * stores it in result.     * stores it in result. *)
    *)  
113      fun mkXOR (result, var1, var2, stmt : IR.var -> IR.stmt) =      fun mkXOR (result, var1, var2, stmt : IR.var -> IR.stmt) =
114            letPRIM("testOR", IR.T_BOOL, IR.OR, [var1, var2], fn testOR =>            letPRIM("testOR", IR.T_BOOL, IR.OR, [var1, var2], fn testOR =>
115            letPRIM("testAND", IR.T_BOOL, IR.AND, [var1, var2], fn testAND =>            letPRIM("testAND", IR.T_BOOL, IR.AND, [var1, var2], fn testAND =>
116            letPRIM("testNAND", IR.T_BOOL, IR.NOT, [testAND], fn testNAND =>            letPRIM("testNAND", IR.T_BOOL, IR.NOT, [testAND], fn testNAND =>
117            letPRIM(result, IR.T_BOOL, IR.AND, [testOR, testNAND], stmt))))            letPRIM(result, IR.T_BOOL, IR.AND, [testOR, testNAND], stmt))))
118    
119        fun genFloatVar (fltVar, env, domain : Float.float P.domain, dist, stmt : IR.var -> IR.stmt) = let
120          fun genRandVal(var, stmt : IR.var -> IR.stmt) = (case dist
121            of P.DIST_UNIFORM =>
122              letPRIM(var, IR.T_FLOAT, IR.RAND, [], stmt)
123    
124             (* The PDF here is f(x) = 2x when 0 < x <= 1, so the CDF is going
125              * to be the integral of f from 0 -> y => y^2. Hence, whenever we
126              * generate a random number, in order to get the random value according
127              * to this probability distribution, we just square it. *)
128             | P.DIST_INC_LIN =>
129              letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
130              letPRIM(var, IR.T_FLOAT, IR.MULT, [randVal, randVal], stmt))
131    
132             (* The PDF here is f(x) = -2x + 2 when 0 <= x < 1, so the CDF is going
133              * to be the integral of f from 0 -> y => -(y^2) + 2y. Hence, whenever we
134              * generate a random number, in order to get the random value according
135              * to this probability distribution, we just square it.
136              *)
137             | P.DIST_DEC_LIN =>
138              letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
139              letPRIM("randSq", IR.T_FLOAT, IR.MULT, [randVal, randVal], fn randSq =>
140              letPRIM("termOne", IR.T_FLOAT, IR.MULT, [randSq, IR.newConst("negOne", IR.C_FLOAT ~1.0)], fn termOne =>
141              letPRIM("termTwo", IR.T_FLOAT, IR.MULT, [randVal, IR.newConst("negOne", IR.C_FLOAT 2.0)], fn termTwo =>
142              letPRIM(var, IR.T_FLOAT, IR.ADD, [termOne, termTwo], stmt)
143              ))))
144    
145             | _ => raise Fail "Unable to create random float for specified distribution"
146           (* end case *))
147         in
148         (case domain
149          of P.D_POINT(pt) =>
150             (* Our options here are pretty limited... *)
151             letPRIM (fltVar, IR.T_FLOAT, IR.COPY, [psvToIRVar(env, pt)], stmt)
152    
153           | P.D_BOX{max, min} =>
154             genRandVal("randf", fn rand =>
155             letPRIM("boxDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, max), psvToIRVar(env, max)], fn diff =>
156             letPRIM("scale", IR.T_FLOAT, IR.MULT, [diff, rand], fn scale =>
157             letPRIM( fltVar, IR.T_FLOAT, IR.ADD, [psvToIRVar(env, max), scale], stmt )
158             )))
159           | _ => raise Fail ("Cannot generate float in specified domain: " ^ (P.dToStr domain))
160         (* end case *))
161        end
162    
163    (* Generates a random vector within the given domain and puts it in vecVar *)    (* Generates a random vector within the given domain and puts it in vecVar *)
164      fun genVecVar (vecVar, env, domain, stmt : IR.var -> IR.stmt) = (case domain      fun genVecVar (
165          vecVar,
166          env,
167          domain : Vec3f.vec3 P.domain,
168          dist : Vec3f.vec3 P.distribution,
169          stmt : IR.var -> IR.stmt
170        ) = (case domain
171             of P.D_POINT(pt) =>             of P.D_POINT(pt) =>
172               (* Our options here are pretty limited... *)               (* Our options here are pretty limited... *)
173                  letPRIM (vecVar, IR.T_VEC, IR.COPY, [psvToIRVar(env, pt)], stmt)                  letPRIM (vecVar, IR.T_VEC, IR.COPY, [psvToIRVar(env, pt)], stmt)
174    
175              | P.D_LINE({pt1, pt2}) =>              | P.D_LINE({pt1, pt2}) =>
176    
177                (* Lerp between the points. *)                (* Lerp between the points. *)
178                  letPRIM ("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>                  letPRIM ("randVal", IR.T_FLOAT, IR.RAND, [], fn randVal =>
179                  letPRIM ("randInv", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), randVal], fn randInv =>                  letPRIM ("randInv", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), randVal], fn randInv =>
# Line 181  Line 219 
219    
220    
221              | P.D_TRIANGLE{pt1, pt2, pt3} =>              | P.D_TRIANGLE{pt1, pt2, pt3} =>
222    
223                  letPRIM ("pt1ToPt2", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn pt1ToPt2 =>                  letPRIM ("pt1ToPt2", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn pt1ToPt2 =>
224                  letPRIM ("pt1ToPt3", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt3), psvToIRVar(env, pt1)], fn pt1ToPt3 =>                  letPRIM ("pt1ToPt3", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt3), psvToIRVar(env, pt1)], fn pt1ToPt3 =>
225                  letPRIM ("randOne", IR.T_FLOAT, IR.RAND, [], fn rand1 =>                  letPRIM ("randOne", IR.T_FLOAT, IR.RAND, [], fn rand1 =>
# Line 201  Line 240 
240                    letPRIM("htInv", IR.T_FLOAT, IR.DIV, [IR.newConst("one", IR.C_FLOAT 1.0), height], fn htInv =>                    letPRIM("htInv", IR.T_FLOAT, IR.DIV, [IR.newConst("one", IR.C_FLOAT 1.0), height], fn htInv =>
241                    letPRIM("n", IR.T_VEC, IR.SCALE, [htInv, normVec], fn norm =>                    letPRIM("n", IR.T_VEC, IR.SCALE, [htInv, normVec], fn norm =>
242                    (* Generate a point in the lower disc. *)                    (* Generate a point in the lower disc. *)
243                      genVecVar("ptInDisc", insert(env, normVar, norm), P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad}, fn ptInDisc =>                      genVecVar("ptInDisc",
244                          insertVar(env, normVar, norm),
245                          P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},
246                          dist,
247                          fn ptInDisc =>
248                    (* Now add this point to a random scaling of the normVec. *)                    (* Now add this point to a random scaling of the normVec. *)
249                      letPRIM("s", IR.T_FLOAT, IR.MULT, [height, ourRand], fn scale =>                      letPRIM("s", IR.T_FLOAT, IR.MULT, [height, ourRand], fn scale =>
250                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, normVec], fn scaledNormVec =>                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, normVec], fn scaledNormVec =>
# Line 209  Line 252 
252                   end                   end
253    
254              | P.D_DISC {pt, normal, irad, orad} =>              | P.D_DISC {pt, normal, irad, orad} =>
255    
256                (* Get a random angle... *)                (* Get a random angle... *)
257                  letPRIM ("r", IR.T_FLOAT, IR.RAND, [], fn randForAng =>                  letPRIM ("r", IR.T_FLOAT, IR.RAND, [], fn randForAng =>
258                  letPRIM ("t", IR.T_FLOAT, IR.MULT, [randForAng, IR.newConst("fullCir", IR.C_FLOAT (2.0 * pi))], fn randAng =>                  letPRIM ("t", IR.T_FLOAT, IR.MULT, [randForAng, IR.newConst("fullCir", IR.C_FLOAT (2.0 * pi))], fn randAng =>
259    
260                (* Get a random radius *)                (* Get a random radius *)
261                  letPRIM ("e0", IR.T_FLOAT, IR.RAND, [], fn newRand =>                  letPRIM ("e0", IR.T_FLOAT, IR.RAND, [], fn newRand =>
262                  letPRIM ("e0sq", IR.T_FLOAT, IR.MULT, [newRand, newRand], fn randRadSq =>              letPRIM ("e0sq", IR.T_FLOAT, IR.SQRT, [newRand], fn randRadSq =>
263                  letPRIM ("radDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, orad), psvToIRVar(env, irad)], fn radDiff =>                  letPRIM ("radDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, orad), psvToIRVar(env, irad)], fn radDiff =>
264                  letPRIM ("newRadDist", IR.T_FLOAT, IR.MULT, [randRadSq, radDiff], fn newRadDist =>                  letPRIM ("newRadDist", IR.T_FLOAT, IR.MULT, [randRadSq, radDiff], fn newRadDist =>
265                  letPRIM ("newRad", IR.T_FLOAT, IR.ADD, [psvToIRVar(env, irad), newRadDist], fn newRad =>                  letPRIM ("newRad", IR.T_FLOAT, IR.ADD, [psvToIRVar(env, irad), newRadDist], fn newRad =>
266    
267                (* Find a vector in the plane of the disc, and then                (* Find a vector in the plane of the disc, and then
268                 * translate it to the center.               * translate it to the center. *)
                *)  
269                  letPRIM ("ntoc", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn normToCen =>                  letPRIM ("ntoc", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn normToCen =>
270                  letPRIM ("v", IR.T_VEC, IR.CROSS, [psvToIRVar(env, pt), normToCen], fn vecInDisc =>                  letPRIM ("v", IR.T_VEC, IR.CROSS, [psvToIRVar(env, pt), normToCen], fn vecInDisc =>
271                  letPRIM ("vidn", IR.T_VEC, IR.NORM, [vecInDisc], fn vecInDiscNorm =>                  letPRIM ("vidn", IR.T_VEC, IR.NORM, [vecInDisc], fn vecInDiscNorm =>
272                  letPRIM ("p", IR.T_VEC, IR.CROSS, [vecInDiscNorm, psvToIRVar(env, normal)], fn ptInDisc =>                  letPRIM ("p", IR.T_VEC, IR.CROSS, [vecInDiscNorm, psvToIRVar(env, normal)], fn ptInDisc =>
273                  letPRIM ("pidn", IR.T_VEC, IR.NORM, [ptInDisc], fn ptInDiscNorm =>                  letPRIM ("pidn", IR.T_VEC, IR.NORM, [ptInDisc], fn ptInDiscNorm =>
274    
275                (* Figure out x and y values for our new radius and angle *)                (* Figure out x and y values for our new radius and angle *)
276                  letPRIM ("rx", IR.T_FLOAT, IR.COS, [randAng], fn radX =>                  letPRIM ("rx", IR.T_FLOAT, IR.COS, [randAng], fn radX =>
277                  letPRIM ("ar1", IR.T_FLOAT, IR.MULT, [newRad, radX], fn amtVecOne =>                  letPRIM ("ar1", IR.T_FLOAT, IR.MULT, [newRad, radX], fn amtVecOne =>
# Line 234  Line 280 
280                  letPRIM ("ar2", IR.T_FLOAT, IR.MULT, [newRad, radY], fn amtVecTwo =>                  letPRIM ("ar2", IR.T_FLOAT, IR.MULT, [newRad, radY], fn amtVecTwo =>
281                  letPRIM ("rv2", IR.T_VEC, IR.SCALE, [amtVecTwo, ptInDiscNorm], fn resVecTwo =>                  letPRIM ("rv2", IR.T_VEC, IR.SCALE, [amtVecTwo, ptInDiscNorm], fn resVecTwo =>
282                  letPRIM ("res", IR.T_VEC, IR.ADD_VEC, [resVecOne, resVecTwo], fn result =>                  letPRIM ("res", IR.T_VEC, IR.ADD_VEC, [resVecOne, resVecTwo], fn result =>
                 letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [result, psvToIRVar(env, pt)], stmt))))))))))))))))))))  
283    
284                letPRIM (vecVar, IR.T_VEC, IR.ADD_VEC, [result, psvToIRVar(env, pt)], stmt)
285                )))))))))))))))))))
286    
287            (* !FIXME! This isn't right. The values will be generated more towards
288             * the tip of the cone than the base. The scale needs to be adjusted based
289             * on the area of the base (although I don't know how). *)
290              | P.D_CONE{pt1, pt2, irad, orad} => let              | P.D_CONE{pt1, pt2, irad, orad} => let
291                  val normVar = PSV.new("local_ht", PSV.T_VEC3F)                  val normVar = PSV.new("local_ht", PSV.T_VEC3F)
292                  in                  in
293                    letPRIM("eh",  IR.T_FLOAT, IR.RAND, [], fn ourRand =>                    letPRIM("eh",  IR.T_FLOAT, IR.RAND, [], fn ourRand =>
294                    letPRIM("nv", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn normVec =>                    letPRIM("nv", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn normVec =>
295                    letPRIM("n", IR.T_VEC, IR.NORM, [normVec], fn norm =>                    letPRIM("n", IR.T_VEC, IR.NORM, [normVec], fn norm =>
296                      genVecVar("ptInDisc", insert(env, normVar, norm), P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad}, fn ptInDisc =>               genVecVar("ptInDisc",
297                  insertVar(env, normVar, norm),
298                  P.D_DISC{pt = pt1, normal = normVar, irad = irad, orad = orad},
299                  dist,
300                  fn ptInDisc =>
301                      letPRIM("gptt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), ptInDisc], fn genPtToTip =>                      letPRIM("gptt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), ptInDisc], fn genPtToTip =>
302                      letPRIM("gpttlen", IR.T_FLOAT, IR.LEN, [genPtToTip], fn genPtToTipLen =>                      letPRIM("gpttlen", IR.T_FLOAT, IR.LEN, [genPtToTip], fn genPtToTipLen =>
303                      letPRIM("s", IR.T_FLOAT, IR.MULT, [genPtToTipLen, ourRand], fn scale =>                      letPRIM("s", IR.T_FLOAT, IR.MULT, [genPtToTipLen, ourRand], fn scale =>
304                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, genPtToTip], fn scaledNormVec =>                      letPRIM("sn", IR.T_VEC, IR.SCALE, [scale, genPtToTip], fn scaledNormVec =>
305                      letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [ptInDisc, scaledNormVec], stmt)))))))))               letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [ptInDisc, scaledNormVec], stmt)
306                 ))))))))
307                  end                  end
308    
309              | _ => raise Fail "Cannot generate point in specified domain."                  | P.D_SPHERE{center, irad, orad} =>
310            (* end case *))  
311            (*                    (* Source: http://mathworld.wolfram.com/SpherePointPicking.html *)
312            | generate (Dplane{pt, n}) = Vec3f.unpack pt  
313        | generate (Drectangle{pt, u, v}) = Vec3f.unpack pt            (* generate two random values... one will be called u and will
314        | generate (Dsphere{c, orad, irad}) = Vec3f.unpack c             * represent cos(theta), and the other will be called v and will
315        | generate (Dblob{c, stddev}) = Vec3f.unpack c             * represent a random value in [0, 2 * pi] *)
316            *)            letPRIM("randVal", IR.T_FLOAT, IR.RAND, [], fn rv =>
317              letPRIM("dblRandVal", IR.T_FLOAT, IR.MULT, [rv, IR.newConst("Two", IR.C_FLOAT 2.0)], fn drv =>
318              letPRIM("rand", IR.T_FLOAT, IR.SUB, [drv, IR.newConst("One", IR.C_FLOAT 1.0)], fn u =>
319    
320              letPRIM("rv2", IR.T_FLOAT, IR.RAND, [], fn rv2 =>
321              letPRIM("rand2", IR.T_FLOAT, IR.MULT, [rv2, IR.newConst("TwoPi", IR.C_FLOAT (2.0 * Float.M_PI))], fn theta =>
322    
323              letPRIM("cosTheta", IR.T_FLOAT, IR.COS, [theta], fn cosT =>
324              letPRIM("sinTheta", IR.T_FLOAT, IR.SIN, [theta], fn sinT =>
325    
326              letPRIM("usq", IR.T_FLOAT, IR.MULT, [u, u], fn usq =>
327              letPRIM("usqInv", IR.T_FLOAT, IR.SUB, [IR.newConst("One", IR.C_FLOAT 1.0), usq], fn usqInv =>
328              letPRIM("sinPhi", IR.T_FLOAT, IR.SQRT, [usqInv], fn sinP =>
329    
330              letPRIM("xVal", IR.T_FLOAT, IR.MULT, [sinP, cosT], fn xVal =>
331              letPRIM("yVal", IR.T_FLOAT, IR.MULT, [sinP, sinT], fn yVal =>
332              (* zval is just u *)
333    
334              letPRIM("vec", IR.T_VEC, IR.GEN_VEC, [xVal, yVal, u], fn vec =>
335    
336              (* Generate a random radius... *)
337                      letPRIM("ratio", IR.T_FLOAT, IR.DIV, [psvToIRVar(env, irad), psvToIRVar(env, orad)], fn ratio =>
338                      letPRIM("invRatio", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), ratio], fn invRatio =>
339                      letPRIM("randVar", IR.T_FLOAT, IR.RAND, [], fn rand =>
340                      letPRIM("randScale", IR.T_FLOAT, IR.MULT, [rand, invRatio], fn randScale =>
341                      letPRIM("randVal", IR.T_FLOAT, IR.ADD, [randScale, ratio], fn randVal =>
342                      letPRIM("randValSq", IR.T_FLOAT, IR.SQRT, [randVal], fn randValSq =>
343                      letPRIM("radDiff", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, orad), psvToIRVar(env, irad)], fn radDiff =>
344                      letPRIM("randRadVal", IR.T_FLOAT, IR.MULT, [radDiff, randValSq], fn randRadVal =>
345                      letPRIM("rad", IR.T_FLOAT, IR.ADD, [psvToIRVar(env, irad), randRadVal], fn rad =>
346    
347                      (* Normalize the vector and scale it by the radius. *)
348                      letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [rad, vec], fn sVec =>
349                      letPRIM(vecVar, IR.T_VEC, IR.ADD_VEC, [sVec, psvToIRVar(env, center)], stmt)
350                      ))))))))))
351                      )))))))))))))
352    
353                | _ => raise Fail ("Cannot generate point in specified domain: "  ^ (P.dToStr domain))
354              (* end case *))
355    
356    (* This function takes an IR boolean, its environment, a particle state, domain,    (* This function takes an IR boolean, its environment, a particle state, domain,
357     * and continuation.     * and continuation.
# Line 266  Line 359 
359     * We set the boolean to whether or not the current particle given by the particle     * We set the boolean to whether or not the current particle given by the particle
360     * state is within the domain, and then pass the continuation on.     * state is within the domain, and then pass the continuation on.
361     *)     *)
362      fun mkWithinVar (boolVar, env, var, d, stmt : IR.var -> IR.stmt) = let      fun mkVecWithinVar (boolVar, env, var, d : Vec3f.vec3 P.domain, stmt : IR.var -> IR.stmt) = let
363            val pos = var            val pos = var
364            in            in
365              case d              case d
# Line 335  Line 428 
428                    letPRIM("inOrad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), posToCLen], fn inOrad =>                    letPRIM("inOrad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), posToCLen], fn inOrad =>
429                    letPRIM("inIrad", IR.T_BOOL, IR.GT, [posToCLen, psvToIRVar(env, irad)], fn inIrad =>                    letPRIM("inIrad", IR.T_BOOL, IR.GT, [posToCLen, psvToIRVar(env, irad)], fn inIrad =>
430                    letPRIM(boolVar, IR.T_BOOL, IR.AND, [inIrad, inOrad], stmt)))))                    letPRIM(boolVar, IR.T_BOOL, IR.AND, [inIrad, inOrad], stmt)))))
431    
432                      | P.D_CYLINDER {pt1, pt2, irad, orad} =>
433    
434                      (* !FIXME! Right now, we see whether or not the point is within the two planes defined
435                       * by the endpoints of the cylinder, and then testing to see whether or not the smallest
436                       * distance to the line segment falls within the radii. It might be faster to find the
437                       * closest point to the line defined by the endpoints and then see whether or not the point
438                       * is within the segment.
439                       *)
440    
441                      (* Is it in one plane *)
442                      letPRIM("plane1Norm", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn plane1Norm =>
443                      letPRIM("posToPt1", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, pt1)], fn posToPt1 =>
444                      letPRIM("dot1", IR.T_FLOAT, IR.DOT, [posToPt1, plane1Norm], fn dot1Prod =>
445                      letPRIM("inPlane1", IR.T_BOOL, IR.GT, [dot1Prod, IR.newConst("zero", IR.C_FLOAT 0.0)], fn inPlane1=>
446    
447                      (* Is it in another plane *)
448                      letPRIM("plane2Norm", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt1), psvToIRVar(env, pt2)], fn plane2Norm =>
449                      letPRIM("posToPt2", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, pt2)], fn posToPt2 =>
450                      letPRIM("dot2", IR.T_FLOAT, IR.DOT, [posToPt2, plane2Norm], fn dot2Prod =>
451                      letPRIM("inPlane2", IR.T_BOOL, IR.GT, [dot2Prod, IR.newConst("zero", IR.C_FLOAT 0.0)], fn inPlane2=>
452    
453                      (* Is it in both planes? *)
454                      letPRIM("inPlanes", IR.T_BOOL, IR.AND, [inPlane1, inPlane2], fn inPlanes =>
455    
456                      (* Find distance from segment *)
457                      letPRIM("a", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt2), psvToIRVar(env, pt1)], fn a =>
458                      letPRIM("b", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt1), pos], fn b =>
459                      letPRIM("alen", IR.T_FLOAT, IR.LEN, [a], fn alen =>
460                      letPRIM("axb", IR.T_VEC, IR.CROSS, [a, b], fn axb =>
461                      letPRIM("axblen", IR.T_FLOAT, IR.LEN, [axb], fn axblen =>
462                      letPRIM("dist", IR.T_FLOAT, IR.DIV, [axblen, alen], fn dist =>
463    
464                      (* Is distance in both radii? *)
465                      letPRIM("inOradGt", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), dist], fn inOradGt =>
466                      letPRIM("inOradEq", IR.T_BOOL, IR.EQUALS, [psvToIRVar(env, orad), dist], fn inOradEq =>
467                      letPRIM("inOrad", IR.T_BOOL, IR.OR, [inOradGt, inOradEq], fn inOrad =>
468    
469                      letPRIM("inIradGt", IR.T_BOOL, IR.GT, [dist, psvToIRVar(env, irad)], fn inIradGt =>
470                      letPRIM("inIradEq", IR.T_BOOL, IR.EQUALS, [dist, psvToIRVar(env, irad)], fn inIradEq =>
471                      letPRIM("inIrad", IR.T_BOOL, IR.OR, [inIradGt, inIradEq], fn inIrad =>
472    
473                      letPRIM("inBothRad", IR.T_BOOL, IR.AND, [inIrad, inOrad], fn inBothRad =>
474    
475                      (* It's in the cylinder (tube) if it's within both radii and in both planes... *)
476                      letPRIM(boolVar, IR.T_BOOL, IR.AND, [inPlanes, inBothRad], stmt)
477                      ))))))))))))))))))))))
478  (*  (*
479                | P.D_TRIANGLE {pt1: vec3f var, pt2: vec3f var, pt3: vec3f var}                | P.D_TRIANGLE {pt1: vec3f var, pt2: vec3f var, pt3: vec3f var}
480                | P.D_PLANE {pt: vec3f var, normal: vec3f var}                | P.D_PLANE {pt: vec3f var, normal: vec3f var}
481                | P.D_RECT {pt: vec3f var, htvec: vec3f var, wdvec: vec3f var}                | P.D_RECT {pt: vec3f var, htvec: vec3f var, wdvec: vec3f var}
482                | P.D_BOX {min: vec3f var, max: vec3f var}                | P.D_BOX {min: vec3f var, max: vec3f var}
483                | P.D_SPHERE {center: vec3f var, irad: vec3f var, orad: vec3f var}                | P.D_SPHERE {center: vec3f var, irad: vec3f var, orad: vec3f var}
               | P.D_CYLINDER {pt1: vec3f var, pt2: vec3f var, irad: float var, orad: float var}  
484                | P.D_CONE {pt1: vec3f var, pt2: vec3f var, irad: float var, orad: float var}                | P.D_CONE {pt1: vec3f var, pt2: vec3f var, irad: float var, orad: float var}
485                | P.D_BLOB {center: vec3f var, stddev: float var}                | P.D_BLOB {center: vec3f var, stddev: float var}
486                | P.D_DISC {pt: vec3f var, normal: vec3f var, irad: float var, orad: float var}                | P.D_DISC {pt: vec3f var, normal: vec3f var, irad: float var, orad: float var}
487  *)  *)
488                | _ => raise Fail "Cannot determine within-ness for specified domain."                | _ => raise Fail ("Cannot determine within-ness for specified vec3 domain: " ^ (P.dToStr d))
489              (* end case *)              (* end case *)
490            end (*end let *)            end (*end let *)
491    
492            fun mkFloatWithinVar (boolVar, env, var, d : Float.float P.domain, stmt : IR.var -> IR.stmt) = (case d
493              of P.D_POINT(pt) => letPRIM(boolVar, IR.T_BOOL, IR.EQUALS, [psvToIRVar(env, pt), var], stmt)
494               | P.D_BOX {min, max} =>
495                 letPRIM("bigMin", IR.T_BOOL, IR.GT, [var, psvToIRVar(env, min)], fn bigMin =>
496                 letPRIM("smallMax", IR.T_BOOL, IR.GT, [psvToIRVar(env, max), var], fn smallMax =>
497                 letPRIM(boolVar, IR.T_BOOL, IR.AND, [bigMin, smallMax], stmt)))
498               | _ => raise Fail ("Cannot determine within-ness for specified float domain: " ^ (P.dToStr d))
499             (* end case *))
500    
501            fun mkIntBool(env, p1var, p2var, d : Vec3f.vec3 P.domain, k : IR.var -> ir_env -> IR.stmt) = let
502              val _ = ()
503             in
504              (case d
505                of P.D_POINT(pt) =>
506    
507                 (* Get vectors *)
508                 letPRIM("p1ToPt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar (env, pt), p1var], fn p1ToPt =>
509                 letPRIM("p2ToPt", IR.T_VEC, IR.SUB_VEC, [psvToIRVar (env, pt), p2var], fn p2ToPt =>
510                 letPRIM("p1ToP2", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn p1ToP2 =>
511    
512                 (* Get distances *)
513                 letPRIM("p1ToPtLen", IR.T_FLOAT, IR.LEN, [p1ToPt], fn p1ToPtLen =>
514                 letPRIM("p2ToPtLen", IR.T_FLOAT, IR.LEN, [p2ToPt], fn p2ToPtLen =>
515                 letPRIM("p1ToP2Len", IR.T_FLOAT, IR.LEN, [p1ToP2], fn p1ToP2Len =>
516    
517                 (* Add & subtract ... *)
518                 letPRIM("distSum", IR.T_FLOAT, IR.ADD, [p1ToPtLen, p2ToPtLen], fn distSum =>
519                 letPRIM("distDiff", IR.T_FLOAT, IR.SUB, [distSum, p1ToP2Len], fn distDiff =>
520                 letPRIM("distDiffAbs", IR.T_FLOAT, IR.ABS, [distDiff], fn distDiffAbs =>
521    
522                 (* Do the boolean stuff... *)
523                 letPRIM("intersect", IR.T_BOOL, IR.GT, [psvToIRVar(env, epsilon), distDiffAbs], fn intVar => k intVar env)
524    
525                 )))
526                 )))
527                 )))
528    
529    (* generate code to produce a random particle state from a domain *)              | P.D_PLANE {pt, normal} =>
530      fun newParticle (posDomain, velDomain, colDomain, env, k : particle_state -> IR.stmt) =                letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
531              (* genVecVar (vecVar, env, domain, stmt) *)                letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
532              genVecVar("ps_pos", env, posDomain, fn newPos =>                letPRIM("p2d", IR.T_FLOAT, IR.DOT, [p2var, psvToIRVar(env, normal)], fn p2d =>
533              genVecVar("ps_vel", env, velDomain, fn newVel =>                letPRIM("p1dist", IR.T_FLOAT, IR.SUB, [d, p1d], fn p1dist =>
534              genVecVar("ps_col", env, colDomain, fn newCol =>                letPRIM("p2dist", IR.T_FLOAT, IR.SUB, [d, p2d], fn p2dist =>
535              letPRIM ("randSize", IR.T_FLOAT, IR.RAND, [], fn randSize =>                letPRIM("distProd", IR.T_FLOAT, IR.MULT, [p1dist, p2dist], fn distProd =>
536              letPRIM ("halvedSize", IR.T_FLOAT, IR.MULT, [randSize, IR.newConst("halver", IR.C_FLOAT 0.5)], fn halfSize =>                letPRIM("intersect", IR.T_BOOL, IR.GT, [IR.newConst("zero", IR.C_FLOAT 0.0), distProd], fn intVar => k intVar env)
537              letSPRIM("ps_size", IR.T_FLOAT, IR.ADD, [halfSize, IR.newConst("scalar", IR.C_FLOAT 0.5)], fn newSize =>                ))))))
538              letSPRIM ("ps_ttl", IR.T_FLOAT, IR.COPY, [IR.newConst("fbool", IR.C_FLOAT 10000.0)], fn newIsDead =>  
539                k(PS{pos = newPos,              | P.D_DISC {pt, normal, orad, irad} => let
540                     vel = newVel,                val boolVar = IR.newParam("intersect", IR.T_BOOL)
541                     size = newSize,                val newBlk = newBlockWithArgs(env, [boolVar], k boolVar)
542                     ttl = newIsDead,               in
543                     color = newCol,                letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
544                     pos2 = IR.newConst("ps_pos2", IR.C_VEC {x=0.0, y=0.0, z=0.0}),                letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
545                     dummy = IR.newConst("ps_dummy", IR.C_FLOAT 0.01)})  
546                  (* Early out... does it intersect the plane?
547                   *
548                   * !SPEED! Due to the perceived slowness of branching on
549                   * GPUs, this might not actually be faster on all runtime environments *)
550    
551                  letPRIM("p2d", IR.T_FLOAT, IR.DOT, [p2var, psvToIRVar(env, normal)], fn p2d =>
552                  letPRIM("p1dist", IR.T_FLOAT, IR.SUB, [d, p1d], fn p1dist =>
553                  letPRIM("p2dist", IR.T_FLOAT, IR.SUB, [d, p2d], fn p2dist =>
554                  letPRIM("distProd", IR.T_FLOAT, IR.MULT, [p1dist, p2dist], fn distProd =>
555                  letPRIM("earlyOut", IR.T_BOOL, IR.GT, [distProd, IR.newConst("zero", IR.C_FLOAT 0.0)], fn earlyOut =>
556                  IR.mkIF(earlyOut,
557                    (* then *)
558                    letPRIM("intersect", IR.T_BOOL, IR.NOT, [earlyOut], fn var => gotoWithArgs(env, [var], newBlk)),
559                    (* else *)
560                    letPRIM("v", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn v =>
561                    letPRIM("vDotn", IR.T_FLOAT, IR.DOT, [v, psvToIRVar(env, normal)], fn vdn =>
562                    letPRIM("t", IR.T_FLOAT, IR.DIV, [p1dist, vdn], fn t =>
563    
564                    (* !TODO! Add some sort of assert mechanism to make sure that t is
565                     * in the interval [0, 1]... *)
566                    letPRIM("vscale", IR.T_VEC, IR.SCALE, [t, v], fn vscale =>
567                    letPRIM("ppt", IR.T_VEC, IR.ADD_VEC, [p1var, vscale], fn ppt =>
568                    letPRIM("lenVec", IR.T_VEC, IR.SUB_VEC, [ppt, psvToIRVar(env, pt)], fn cv =>
569                    letPRIM("len", IR.T_FLOAT, IR.LEN, [cv], fn len =>
570    
571                    (* Check to see whether or not it's within the radius... *)
572                    letPRIM("gtirad", IR.T_BOOL, IR.GT, [len, psvToIRVar(env, irad)], fn gtirad =>
573                    letPRIM("ltorad", IR.T_BOOL, IR.GT, [psvToIRVar(env, orad), len], fn ltorad =>
574                    letPRIM("intersect", IR.T_BOOL, IR.AND, [gtirad, ltorad], fn var => gotoWithArgs(env, [var], newBlk))
575                   ))))))))))
576                 )))))))
577                end (* P.D_DISC *)
578    
579                | _ => raise Fail ("Cannot calculate intersection bool for specified domain: " ^ (P.dToStr d))
580              (* end case *))
581    
582             end (* mkIntBool *)
583    
584            (* We assume that the segment already intersects with the domain. *)
585            fun mkIntPt(env, p1var, p2var, d : Vec3f.vec3 P.domain, k : IR.var -> IR.stmt) = let
586              val _ = ()
587             in
588              (case d
589                of P.D_POINT(pt) => k (psvToIRVar (env, pt))
590    
591                 | P.D_PLANE {pt, normal} =>
592                   letPRIM("d", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, pt), psvToIRVar(env, normal)], fn d =>
593                   letPRIM("p1d", IR.T_FLOAT, IR.DOT, [p1var, psvToIRVar(env, normal)], fn p1d =>
594                   letPRIM("num", IR.T_FLOAT, IR.SUB, [d, p1d], fn num =>
595                   letPRIM("v", IR.T_VEC, IR.SUB_VEC, [p2var, p1var], fn v =>
596                   letPRIM("den", IR.T_FLOAT, IR.DOT, [v, psvToIRVar(env, normal)], fn den =>
597                   letPRIM("t", IR.T_FLOAT, IR.DIV, [num, den], fn t =>
598                   letPRIM("vsc", IR.T_VEC, IR.SCALE, [t, v], fn vs =>
599                   letPRIM("intPt", IR.T_VEC, IR.ADD_VEC, [p1var, vs], k)
600              )))))))              )))))))
601    
602                 (* Since we already know they intersect, the intersection point must be
603                  * just the point that's on the plane... *)
604                 | P.D_DISC {pt, normal, orad, irad} => mkIntPt(env, p1var, p2var, P.D_PLANE{pt = pt, normal = normal}, k)
605                 | _ => raise Fail ("Cannot calculate intersection point for specified domain: "  ^ (P.dToStr d))
606              (* end case *))
607             end (* mkIntPt *)
608    
609      (* Find the normal at the given position of the particle for the specified      (* Find the normal at the given position of the particle for the specified
610       * domain. Note, that the particle doesn't necessarily need to be on the       * domain. Note, that the particle doesn't necessarily need to be on the
611       * domain, but if it's not then the behavior is undefined.       * domain, but if it's not then the behavior is undefined. *)
612       *)      fun normAtPoint(retNorm, d, env, pos, k : IR.var -> ir_env -> IR.stmt) = let
     fun normAtPoint(retNorm, d, env, state, k : IR.var -> particle_state -> IR.stmt) = let  
613        val newNorm = IR.newParam("n", IR.T_VEC)        val newNorm = IR.newParam("n", IR.T_VEC)
614        val nextBlk = newBlockWithArgs(env, [newNorm], k(newNorm))        val nextBlk = newBlockWithArgs(env, [newNorm], k(newNorm))
       val PS{pos, ...} = state  
615       in       in
616        (case d        (case d
617            of P.D_PLANE{pt, normal} => letPRIM(retNorm, IR.T_VEC, IR.COPY, [psvToIRVar(env, normal)],            of P.D_PLANE{pt, normal} =>
618                fn newNormVar => gotoWithArgs(state, [newNormVar], nextBlk))               letPRIM("inVec", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, pt), pos], fn inVec =>
619                 letPRIM("dotNorm", IR.T_FLOAT, IR.DOT, [psvToIRVar(env, normal), inVec], fn dotNorm =>
620                 letPRIM("absDot", IR.T_FLOAT, IR.ABS, [dotNorm], fn absDot =>
621                 letPRIM("avoidZero", IR.T_FLOAT, IR.MAX, [psvToIRVar(env, epsilon), absDot], fn dot =>
622             letPRIM("dnRecip", IR.T_FLOAT, IR.DIV, [IR.newConst("One", IR.C_FLOAT 1.0), dot], fn dnRecip =>
623             letPRIM("sign", IR.T_FLOAT, IR.MULT, [dnRecip, dotNorm], fn sign =>
624             letPRIM(retNorm, IR.T_VEC, IR.SCALE, [sign, psvToIRVar(env, normal)],
625               fn newNormVar => gotoWithArgs(env, [newNormVar], nextBlk)))))
626             )))
627    
628             | P.D_DISC{pt, normal, irad, orad} =>             | P.D_DISC{pt, normal, irad, orad} =>
629                mkWithinVar("inP", env, pos, d, fn inPlane =>                normAtPoint(retNorm, P.D_PLANE{pt=pt, normal=normal}, env, pos, k)
                   IR.mkIF(inPlane,  
                     (* then *)  
                     letPRIM(retNorm, IR.T_VEC, IR.COPY, [psvToIRVar(env, normal)],  
                       fn newNormVar => gotoWithArgs(state, [newNormVar], nextBlk)),  
                     (* else *)  
                     letPRIM(retNorm,  
                       IR.T_VEC,  
                           IR.SCALE,  
                           [IR.newConst("negOne", IR.C_FLOAT ~1.0), psvToIRVar(env, normal)],  
                           fn newNormVar => gotoWithArgs(state, [newNormVar], nextBlk))  
                    )  
                  )  
630    
631             | P.D_SPHERE{center, irad, orad} => let             | P.D_SPHERE{center, irad, orad} =>
               val PS{pos, ...} = state  
               in  
632                      letPRIM("sv", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, center)], fn subVec =>                      letPRIM("sv", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, center)], fn subVec =>
633                  letPRIM(retNorm, IR.T_VEC, IR.NORM, [subVec], fn newNormVar => k newNormVar state                  letPRIM(retNorm, IR.T_VEC, IR.NORM, [subVec], fn newNormVar => k newNormVar env
634                      ))                      ))
635    
636               | _ => raise Fail("Cannot find normal to point of specified domain." ^ (P.dToStr d))
637             (* end case *))
638                end                end
639    
640             | _ => raise Fail("Cannot find normal to point of specified domain.")          fun trExpr(expr, env, k : IR.var -> ir_env -> IR.stmt) = (case expr
641              of P.CONSTF f => k (IR.newConst ("c", IR.C_FLOAT f)) env
642    
643           | P.CONST3F v => k (IR.newConst ("c", IR.C_VEC v)) env
644    
645           | P.VAR v => k (psvToIRVar (env, v)) env
646    
647           | P.STATE_VAR sv => k (pssvToIRVar (env, sv)) env
648    
649           | P.GENERATE3F (dom, dist) => genVecVar("genVec", env, dom, dist, fn var => k var env)
650    
651           | P.GENERATEF (dom, dist) => genFloatVar("genFlt", env, dom, dist, fn var => k var env)
652    
653           | P.ADD(e1, e2) =>
654             trExpr(e1, env, fn e1var => fn env' =>
655             trExpr(e2, env', fn e2var => fn env'' =>
656             let
657              val IR.V{varType=vt1, ...} = e1var
658              val IR.V{varType=vt2, ...} = e2var
659             in
660              (case (vt1, vt2)
661                of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("addVar", IR.T_FLOAT, IR.ADD, [e1var, e2var], fn var => k var env'')
662                 | (IR.T_VEC, IR.T_VEC) => letPRIM("addVar", IR.T_VEC, IR.ADD_VEC, [e1var, e2var], fn var => k var env'')
663                 | _ => raise Fail ("Type mismatch to ADD expression")
664              (* end case *))
665             end))
666    
667           | P.SCALE (e1, e2) =>
668             trExpr(e1, env, fn e1var => fn env' =>
669             trExpr(e2, env', fn e2var => fn env'' =>
670             let
671              val IR.V{varType=vt1, ...} = e1var
672              val IR.V{varType=vt2, ...} = e2var
673             in
674              (case (vt1, vt2)
675                of (IR.T_FLOAT, IR.T_VEC) => letPRIM("scaleVar", IR.T_VEC, IR.SCALE, [e1var, e2var], fn var => k var env'')
676                 | (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("scaleVar", IR.T_FLOAT, IR.MULT, [e1var, e2var], fn var => k var env'')
677                 | _ => raise Fail (String.concat["Type mismatch to SCALE expression: ", IR.ty2Str vt1, ", ", IR.ty2Str vt2])
678           (* end case *))           (* end case *))
679             end))
680    
681           | P.DIV (e1, e2) =>
682             trExpr(e1, env, fn e1var => fn env' =>
683             trExpr(e2, env', fn e2var => fn env'' =>
684             let
685              val IR.V{varType=vt1, ...} = e1var
686              val IR.V{varType=vt2, ...} = e2var
687             in
688              (case (vt1, vt2)
689                of (IR.T_FLOAT, IR.T_FLOAT) => letPRIM("divVar", IR.T_FLOAT, IR.DIV, [e1var, e2var], fn var => k var env'')
690                 | _ => raise Fail (String.concat["Type mismatch to DIV expression: ", IR.ty2Str vt1, ", ", IR.ty2Str vt2])
691              (* end case *))
692             end))
693    
694           | P.NEG e =>
695             trExpr(e, env, fn evar => fn env' =>
696             let
697              val IR.V{varType, ...} = evar
698             in
699              (case varType
700                of IR.T_FLOAT => letPRIM("negVar", IR.T_FLOAT, IR.MULT, [evar, IR.newConst("negOne", IR.C_FLOAT ~1.0)], fn var => k var env')
701                 | IR.T_VEC => letPRIM("negVar", IR.T_VEC, IR.NEG_VEC, [evar], fn var => k var env')
702                 | _ => raise Fail ("Type mismatch to NEG expression")
703              (* end case *))
704             end)
705    
706           | P.DOT (e1, e2) =>
707             trExpr(e1, env, fn e1var => fn env' =>
708             trExpr(e2, env', fn e2var => fn env'' =>
709             let
710              val IR.V{varType=vt1, ...} = e1var
711              val IR.V{varType=vt2, ...} = e2var
712             in
713              (case (vt1, vt2)
714                of (IR.T_VEC, IR.T_VEC) => letPRIM("dotVar", IR.T_FLOAT, IR.DOT, [e1var, e2var], fn var => k var env'')
715                 | _ => raise Fail ("Type mismatch to DOT expression")
716              (* end case *))
717             end))
718    
719           | P.CROSS (e1, e2) =>
720             trExpr(e1, env, fn e1var => fn env' =>
721             trExpr(e2, env', fn e2var => fn env'' =>
722             let
723              val IR.V{varType=vt1, ...} = e1var
724              val IR.V{varType=vt2, ...} = e2var
725             in
726              (case (vt1, vt2)
727                of (IR.T_VEC, IR.T_VEC) => letPRIM("crossVar", IR.T_VEC, IR.CROSS, [e1var, e2var], fn var => k var env'')
728                 | _ => raise Fail ("Type mismatch to CROSS expression")
729              (* end case *))
730             end))
731    
732           | P.NORMALIZE e =>
733             trExpr(e, env, fn evar => fn env' =>
734             let
735              val IR.V{varType, ...} = evar
736             in
737              (case varType
738                of IR.T_VEC => letPRIM("normVar", IR.T_VEC, IR.NORM, [evar], fn var => k var env')
739                 | _ => raise Fail ("Type mismatch to NORMALIZE expression")
740              (* end case *))
741             end)
742    
743           | P.LENGTH e =>
744             trExpr(e, env, fn evar => fn env' =>
745             let
746              val IR.V{varType, ...} = evar
747             in
748              (case varType
749                of IR.T_VEC => letPRIM("lenVar", IR.T_FLOAT, IR.LEN, [evar], fn var => k var env')
750                 | _ => raise Fail ("Type mismatch to LENGTH expression")
751              (* end case *))
752             end)
753    
754           (* !SPEED! We're assuming that there is an intersection here... *)
755           | P.INTERSECT {p1, p2, d} =>
756             trExpr(p1, env, fn p1var => fn env' =>
757             trExpr(p2, env', fn p2var => fn env'' =>
758             let
759              val IR.V{varType=vt1, ...} = p1var
760              val IR.V{varType=vt2, ...} = p2var
761             in
762              (case (vt1, vt2)
763                of (IR.T_VEC, IR.T_VEC) => mkIntPt(env, p1var, p2var, d, fn var => k var env'')
764                 | _ => raise Fail("Type mismatch to INTERSECT expression")
765              (* end case *))
766             end))
767    
768           | P.NORMALTO (e, d) =>
769             trExpr(e, env, fn evar => fn env' =>
770             let
771              val IR.V{varType, ...} = evar
772              fun cont s = k s
773             in
774              (case varType
775                of IR.T_VEC => normAtPoint("normVar", d, env', evar, k)
776                 | _ => raise Fail("Type mismatch to NORMALTO expression")
777              (* end case *))
778             end)
779    
780              (* end case expr *))
781    
782            (* generate code to produce a random particle state from a domain *)
783        fun newParticle (sv_gens, env, k : ir_env -> IR.stmt) = let
784    
785          fun createVar(P.GEN{var, ...}) = let
786            val P.PSV.SV{name, ty, ...} = var
787           in
788            IR.newLocal("ps_" ^ name, IR.psvTyToIRTy ty, (IR.RAND, []))
789          end          end
790    
791          fun trEmitter(emit, env, state, k : particle_state -> IR.stmt) = let        val newState = List.map createVar sv_gens
792    
793          fun genVar((sv_gen, var), cont) = let
794            val P.GEN{exp, var=svar} = sv_gen
795            val IR.V{varType, ...} = var
796           in
797            fn env' => trExpr(exp, env', fn newVal => fn env'' => cont (insertSVar(env'', svar, newVal)))
798           end (* genVar *)
799    
800         in
801          (List.foldr (fn (x, y) => genVar(x, y)) k (ListPair.zipEq (sv_gens, newState))) env
802         end (* new particle *)
803    
804            val PS{ttl, ...} = state      fun trEmitter(emit, env, k) = let
805            val P.EMIT{maxNum, posDomain, velDomain, colDomain, ...} = emit        val P.EMIT{freq, sv_gens} = emit
806            val blk = newBlock (env, k)        val ttl = pssvToIRVar(env, P.sv_ttl)
807           in           in
808            letPRIM("isDead", IR.T_BOOL, IR.GT, [IR.newConst("small", IR.C_FLOAT 0.1), ttl], fn isDead =>            letPRIM("isDead", IR.T_BOOL, IR.GT, [IR.newConst("small", IR.C_FLOAT 0.1), ttl], fn isDead =>
809        IR.mkIF(isDead,        IR.mkIF(isDead,
810         (* then *)         (* then *)
811         letPRIM("t1", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env, maxNum)], fn t1 =>         trExpr(freq, env, fn t1 => fn env' =>
812         letPRIM("t2", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env, PSV.numDead)], fn t2 =>         letPRIM("t2", IR.T_FLOAT, IR.ITOF, [psvToIRVar (env', PSV.numDead)], fn t2 =>
813         letPRIM("prob", IR.T_FLOAT, IR.DIV, [t1, t2], fn prob =>         letPRIM("prob", IR.T_FLOAT, IR.DIV, [t1, t2], fn prob =>
814         letPRIM("r", IR.T_FLOAT, IR.RAND, [], fn r =>         letPRIM("r", IR.T_FLOAT, IR.RAND, [], fn r =>
815         letPRIM("t3", IR.T_BOOL, IR.GT, [prob, r], fn t3 =>         letPRIM("t3", IR.T_BOOL, IR.GT, [prob, r], fn t3 =>
816         IR.mkIF(t3,         IR.mkIF(t3,
817          (* then *)          (* then *)
818          newParticle (posDomain, velDomain, colDomain, env,          newParticle (sv_gens, env', fn env'' => k env''),
          fn state' => retState state'),  
819          (* else *)          (* else *)
820          IR.DISCARD)))))),          IR.DISCARD)))))),
821         (* else *)         (* else *)
822         retState state))         k env))
      end  
   
         fun trPred(pred, env, state, thenk : particle_state -> IR.stmt, elsek : particle_state -> IR.stmt) = let  
           val PS{pos, vel, ...} = state  
           val P.PR{ifstmt, ...} = pred  
          in  
           case ifstmt  
            of P.WITHIN(d) => mkWithinVar("wv", env, pos, d, fn withinVar =>  
             IR.mkIF(withinVar, thenk(state), elsek(state)))  
             | P.WITHINVEL(d) => mkWithinVar("wv", env, vel, d, fn withinVar =>  
             IR.mkIF(withinVar, thenk(state), elsek(state)))  
          end  
   
     fun trAct (action, env, state, k : particle_state -> IR.stmt) = let  
           val PS{pos, vel, size, ttl, color, pos2, dummy} = state  
           in  
             case action  
              of P.BOUNCE{friction, resilience, cutoff, d} => let  
                   val blk = newBlock (env, k)  
                   val negOne = IR.newConst("negOne", IR.C_FLOAT ~1.0)  
                   in  
                     letPRIM("vs", IR.T_VEC, IR.SCALE, [psvToIRVar(env, PSV.timeStep), vel], fn velScale =>  
                     letPRIM("np", IR.T_VEC, IR.ADD_VEC, [pos, velScale], fn nextPos =>  
                     mkWithinVar("wcp", env, pos, d, fn withinCurPos =>  
                     mkWithinVar("wnp", env, nextPos, d, fn withinNextPos =>  
                     letPRIM("nwcp", IR.T_BOOL, IR.NOT, [withinCurPos], fn notWithinCurPos =>  
                     letPRIM("sb", IR.T_BOOL, IR.AND, [notWithinCurPos, withinNextPos], fn shouldBounce =>  
                     IR.mkIF(shouldBounce,  
                       (*then*)  
                         normAtPoint("n", d, env, state, fn normAtD => fn state' => let  
                val PS{pos=nextPos, vel=nextVel, size=nextSize, ttl=nextIsDead, color=nextColor, pos2=nextPos2, dummy=nextDummy} = state'  
                           in  
                            letPRIM("negVel", IR.T_VEC, IR.SCALE, [negOne, nextVel], fn negVel =>  
                            letPRIM("dnv", IR.T_FLOAT, IR.DOT, [negVel, normAtD], fn dotNegVel =>  
                            letPRIM("sn", IR.T_VEC, IR.SCALE, [dotNegVel, normAtD], fn scaledN =>  
                            letPRIM("t", IR.T_VEC, IR.SUB_VEC, [negVel, scaledN], fn tang =>  
   
                            letPRIM("tlsq", IR.T_FLOAT, IR.LEN_SQ, [tang], fn tangLenSq =>  
                            letPRIM("cosq", IR.T_FLOAT, IR.MULT, [psvToIRVar(env, cutoff), psvToIRVar(env, cutoff)], fn cutoffSq =>  
                            letPRIM("inco", IR.T_BOOL, IR.GT, [tangLenSq, cutoffSq], fn inCutoff =>  
   
                            letPRIM("resNorm", IR.T_VEC, IR.SCALE, [psvToIRVar(env, resilience), scaledN], fn resNorm =>  
   
                            IR.mkIF(inCutoff,  
                              (*then*)  
                              letPRIM("fInv", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), psvToIRVar(env, friction)], fn frictInv =>  
                              letPRIM("f", IR.T_FLOAT, IR.MULT, [negOne, frictInv], fn modFrict =>  
                              letPRIM("fTang", IR.T_VEC, IR.SCALE, [modFrict, tang], fn frictTang =>  
                              letPRIM("newVel", IR.T_VEC, IR.ADD_VEC, [frictTang, resNorm], fn newVel =>  
                               goto(PS{pos=nextPos, vel=newVel, size=nextSize, ttl=nextIsDead, color=nextColor, pos2=nextPos2, dummy=nextDummy}, blk)  
                             )))),  
                              (*else*)  
                              letPRIM("fTang", IR.T_VEC, IR.SCALE, [negOne, tang], fn frictTang =>  
                              letPRIM("ps_vel", IR.T_VEC, IR.ADD_VEC, [frictTang, resNorm], fn newVel =>  
                               goto(PS{pos=nextPos, vel=newVel, size=nextSize, ttl=nextIsDead, color=nextColor, pos2=nextPos2, dummy=nextDummy}, blk)  
                              ))  
                          )))))))))  
                          end  
                       ),  
                       (*else*)  
                       goto(state, blk))))))))  
823                    end                    end
824    
825                | P.ACCEL dir =>      (* trExpr(expr, env, state, k : IR.var -> IR.stmt) *)
826                      letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [psvToIRVar(env, PSV.timeStep), psvToIRVar(env, dir)], fn theScale =>      (* mkFloatWithinVar (boolVar, env, var, d : Float.float P.domain, stmt : IR.var -> IR.stmt) *)
827                      letPRIM("ps_vel", IR.T_VEC, IR.ADD_VEC, [theScale, vel], fn newVel =>      fun trPred(cond, env, thenk : ir_env -> IR.stmt, elsek : ir_env -> IR.stmt) = let
828                        k(PS{pos = pos, vel = newVel, size = size, ttl = ttl, color = color, pos2=pos2, dummy=dummy})))        fun grabVar(cond, env, k : IR.var -> ir_env -> IR.stmt) = (case cond
829            of P.WITHINF(d, expr) =>
830                | P.MOVE =>              trExpr(expr, env, fn checkMe => fn env' =>
831                  letPRIM("scaledVec", IR.T_VEC, IR.SCALE, [psvToIRVar(env, PSV.timeStep), vel], fn theScale =>              mkFloatWithinVar("wv", env', checkMe, d, fn var => k var env'))
832                      letPRIM("ps_pos", IR.T_VEC, IR.ADD_VEC, [theScale, pos], fn newPos =>  
833                        k(PS{pos = newPos, vel = vel, size = size, ttl = ttl, color = color, pos2=pos2, dummy=dummy})))           | P.WITHIN3F(d, expr) =>
834                (*              trExpr(expr, env, fn checkMe => fn env' =>
835                | P.SINK({d, kill_inside}) =>              mkVecWithinVar("wv", env', checkMe, d, fn var => k var env'))
836                      mkWithinVar("isWithin", env, state, d, fn withinVal =>  
837                      mkXOR ("shouldNotKill", withinVal, psvToIRVar(env, kill_inside),           | P.DO_INTERSECT {p1, p2, d} =>
838                        fn shouldNotKill =>             trExpr(p1, env, fn p1var => fn env' =>
839                      letPRIM("shouldKill", IR.T_BOOL, IR.NOT, [shouldNotKill], fn shouldKill =>             trExpr(p2, env', fn p2var => fn env'' =>
840                      letPRIM("isReallyDead", IR.T_BOOL, IR.OR, [shouldKill, ttl], fn isReallyDead =>             mkIntBool(env'', p1var, p2var, d, k)))
841                      k(PS{pos = pos, vel = vel, size = size, ttl = isReallyDead, color = color})  
842                          ))))           | P.GTHAN (e1, e2) =>
843                *)             trExpr(e1, env, fn e1var => fn env' =>
844               trExpr(e2, env, fn e2var => fn env'' =>
845               letPRIM("gtVar", IR.T_BOOL, IR.GT, [e1var, e2var], fn var => k var env'')))
846    
847             | P.AND(c1, c2) =>
848               grabVar(c1, env, fn c1Var => fn env' =>
849               grabVar(c2, env', fn c2Var => fn env'' =>
850               letPRIM("andVar", IR.T_BOOL, IR.AND, [c1Var, c2Var], fn var => k var env'')))
851    
852             | P.OR(c1, c2) =>
853               grabVar(c1, env, fn c1Var => fn env' =>
854               grabVar(c2, env, fn c2Var => fn env'' =>
855               letPRIM("andVar", IR.T_BOOL, IR.OR, [c1Var, c2Var], fn var => k var env'')))
856    
857             | P.XOR(c1, c2) =>
858               grabVar(c1, env, fn c1Var => fn env' =>
859               grabVar(c2, env', fn c2Var => fn env'' =>
860               mkXOR ("xorVar", c1Var, c2Var, fn var => k var env'')))
861    
862             | P.NOT(c) =>
863               grabVar(c, env, fn cvar => fn env' =>
864               letPRIM("notVar", IR.T_BOOL, IR.NOT, [cvar], fn var => k var env'))
865    
866                | P.ORBITLINESEG {endp1, endp2, maxRad, mag} => let          (* end case *))
                   val blk = newBlock (env, k)  
867                  in                  in
868                  letPRIM("subVec", IR.T_VEC, IR.SUB_VEC, [psvToIRVar(env, endp2), psvToIRVar(env, endp1)], fn subVec =>        grabVar(cond, env, fn result => fn env' =>
869                  letPRIM("vecToEndP", IR.T_VEC, IR.SUB_VEC, [pos, psvToIRVar(env, endp1)], fn vecToEndP =>        IR.mkIF(result, thenk(env'), elsek(env')))
                 letPRIM("basis", IR.T_VEC, IR.NORM, [subVec], fn basis =>  
                 letPRIM("parDot", IR.T_FLOAT, IR.DOT, [basis, vecToEndP], fn parDot =>  
                 letPRIM("parVec", IR.T_VEC, IR.SCALE, [parDot, basis], fn parVec =>  
                 letPRIM("closestP", IR.T_VEC, IR.ADD_VEC, [psvToIRVar(env, endp1), parVec], fn closestP =>  
                 letPRIM("vecToP", IR.T_VEC, IR.SUB_VEC, [closestP, pos], fn vecToP =>  
                 letPRIM("distToP", IR.T_FLOAT, IR.LEN, [vecToP], fn distToP =>  
                 letPRIM("effRad", IR.T_FLOAT, IR.SUB, [psvToIRVar(env, maxRad), distToP], fn effRad =>  
                 letPRIM("radInDist", IR.T_BOOL, IR.GT, [psvToIRVar(env, epsilon), effRad], fn radInDist =>  
                 IR.mkIF(radInDist,  
                   (*then*)  
                   goto(state, blk),  
                   (*else*)  
                   letPRIM("magRatio", IR.T_FLOAT, IR.DIV, [distToP, psvToIRVar(env, maxRad)], fn magRatio =>  
                   letPRIM("oneMinMR", IR.T_FLOAT, IR.SUB, [IR.newConst("one", IR.C_FLOAT 1.0), magRatio], fn oneMinMR =>  
                   letPRIM("gravityMag", IR.T_FLOAT, IR.MULT, [oneMinMR, psvToIRVar(env, mag)], fn gravityMag =>  
                   letPRIM("totalMag", IR.T_FLOAT, IR.MULT, [gravityMag, psvToIRVar(env, PSV.timeStep)], fn totMag =>  
                   letPRIM("accVec", IR.T_VEC, IR.SUB_VEC, [closestP, pos], fn accVec =>  
                   letPRIM("acc", IR.T_VEC, IR.SCALE, [totMag, accVec], fn acc =>  
                   letPRIM("ps_vel", IR.T_VEC, IR.ADD_VEC, [vel, acc], fn newVel =>  
                   goto(PS{pos = pos, vel = newVel, size = size, ttl = ttl, color = color, pos2=pos2, dummy=dummy}, blk)  
                   )))))))  
                 )))))))))))  
                 end  
   
               (* just kill it. *)  
               (* | P.DIE => k(PS{pos = pos, vel = vel, size = size, ttl = IR.newConst("falseVar", IR.C_BOOL true), color = color, dummy=dummy}) *)  
               | P.DIE => IR.DISCARD  
               | _ => raise Fail("Action not implemented...")  
             (* end case *)  
870            end            end
871    
872      fun compile (P.PG{      fun compile (P.PG{
873         emit as P.EMIT{maxNum, vars=emitVars, ...},         emit as P.EMIT{freq, sv_gens}, act, render,
874         act as P.PSAE{action=root_act, vars=actionVars},         vars, state_vars, render_vars
        render  
875      }) = let      }) = let
876            val blks = ref[]            val blks = ref[]
877            val env = let  
878          fun printVar (PSV.V{name, id, ...}) =
879            printErr (String.concat[name, ": ", Int.toString id])
880    
881          val v_env = let
882                (* add special globals to free vars *)                (* add special globals to free vars *)
883                  val vars = PSV.Set.union(emitVars, PSV.Set.addList(actionVars, [maxNum, PSV.numDead, PSV.timeStep, epsilon]))          val pgm_vars = PSV.Set.union(PSV.Set.singleton epsilon, vars)
884                  fun ins (x as PSV.V{name, ty, binding, id, ...}, map) = let          fun insv (x as PSV.V{name, ty, binding, id, ...}, map) = let
885                        val x' = (case (ty, !binding)                        val x' = (case (ty, !binding)
886                               of (PSV.T_BOOL,  PSV.UNDEF) => IR.newGlobal(x, IR.T_BOOL)                               of (PSV.T_BOOL,  PSV.UNDEF) => IR.newGlobal(x, IR.T_BOOL)
887                                | (PSV.T_BOOL,  PSV.BOOL boolVal) => IR.newConst(name, IR.C_BOOL(boolVal))                                | (PSV.T_BOOL,  PSV.BOOL boolVal) => IR.newConst(name, IR.C_BOOL(boolVal))
# Line 573  Line 895 
895                              (* end case *))                              (* end case *))
896                        in                        in
897                          PSV.Map.insert (map, x, x')                          PSV.Map.insert (map, x, x')
898                        end                   end (* ins *)
899    
900                  in                  in
901                    TE(blks, PSV.Set.foldl ins PSV.Map.empty vars)                  PSV.Set.foldl insv PSV.Map.empty pgm_vars
902                  end             end (* env *)
903    
904        fun evalActs f [] state = f [] state        fun evalActs theAct env f = (case theAct
             | evalActs f (psa :: psal) state = (case psa  
905                of P.SEQ(acts) => (case acts                of P.SEQ(acts) => (case acts
906                   of [] => raise Fail "Should never reach here."                  of [] => f env
907                    | [act] => trAct(act, env, state, evalActs f psal)                   | oneAct :: rest => evalActs oneAct env (fn env' => (evalActs (P.SEQ(rest)) env' f))
                   | act :: rest => trAct(act, env, state, evalActs f (P.SEQ(rest) :: psal))  
908                  (* end case *))                  (* end case *))
909                 | P.PRED(pred as P.PR{thenstmt=t, elsestmt=e, ...}) => let  
910                     val cblk = newBlock(env, evalActs f psal)                 | P.PRED(cond, thenAct, elseAct) => let
911                     fun trPredActs [] state' = goto(state', cblk)                     val joinBlk = newBlock (env, fn env' => f env')
912                       | trPredActs _ _ = raise Fail "Should never reach here."                     fun joinActs env = goto(env, joinBlk)
913                      in
914                       trPred(cond, env,
915                         fn env' => evalActs thenAct env' joinActs,
916                         fn env' => evalActs elseAct env' joinActs
917                       )
918                      end
919    
920                   | P.DIE => IR.DISCARD
921    
922                   | P.ASSIGN(sv, expr) => let
923                     val PSV.SV{name, ty, ...} = sv
924                    in                    in
925                     trPred(pred, env, state, evalActs trPredActs t, evalActs trPredActs e)                   trExpr(expr, env, fn newVar => fn env' =>
926                     letPRIM("ps_" ^ name, IR.psvTyToIRTy ty, IR.COPY, [newVar],
927                       fn thisVar => f (insertSVar(env', sv, thisVar))))
928                    end                    end
929    
930                (* end case *))                (* end case *))
931    
932            (* At the highest level, we want to return when we reach the end of the action list *)            val sv_env = let
933            fun trActs [] state = let                (* add special globals to free vars *)
934                  val PS{pos, vel, size, ttl, color, pos2, dummy} = state          fun insv (x as PSV.SV{name, ty, ...}, map) = let
935              val x' = IR.newParam("ps_" ^ name, IR.psvTyToIRTy ty)
936                  in                  in
937                    IR.mkRETURN (                    IR.setRenderVar(x', PSV.SVMap.inDomain(render_vars, x));
938                      [ pos, vel, size, ttl, color, pos2, dummy ],                    PSV.SVMap.insert (map, x, x')
939                      [IR.POS, IR.VEL, IR.SZ, IR.TTL, IR.COLOR, IR.POS2, IR.DUMMY]                   end (* ins *)
940                    )  
941                  end (* trActs *)             in
942              | trActs _ _ = raise Fail "Should never reach here"                  PSV.SVSet.foldl insv PSV.SVMap.empty state_vars
943               end (* env *)
944    
945              val env = TE(blks, v_env, sv_env)
946    
947            (* The entry block is the first block of the program, or in other words, the emitter. *)            (* The entry block is the first block of the program, or in other words, the emitter. *)
948            val entryBlock = newBlock (            val emitterBlock = newBlock (env, fn env => trEmitter(emit, env, retState))
949              env,            val physicsBlock = newBlock (env, fn env => evalActs act env retState)
             fn pstate => trEmitter(  
               emit,  
               env,  
               pstate,  
               fn state => evalActs trActs root_act state  
             )  
           )  
950    
951        (* The entry block is the emitter, and the rest of the blocks define the physics processing. *)        (* The entry block is the emitter, and the rest of the blocks define the physics processing. *)
952    
# Line 623  Line 955 
955           | _ => false           | _ => false
956          (* end case *))          (* end case *))
957    
       fun extractVarMap(TE(blks, map)) = map  
   
958            val outPgm = PSysIR.PGM {            val outPgm = PSysIR.PGM {
959              globals = PSV.Map.filter isGlobal (extractVarMap env),              globals = PSV.Map.filter isGlobal v_env,
960          emitter = entryBlock,          emitter = emitterBlock,
961              physics = List.nth(!blks, 1),              physics = physicsBlock,
962              render = render              render = render
963            }            }
964    
965            val optimized = if (Checker.checkIR(outPgm)) then (printErr "Pre-optimization complete."; Optimize.optimizeIR(outPgm)) else outPgm            val optimized = if (Checker.checkIR(outPgm)) then (printErr "\nPre-optimization complete."; Optimize.optimizeIR(outPgm)) else outPgm
   
966            in            in
967              (* IR.outputPgm(TextIO.stdErr, outPgm); *)              (* Note: it only succeeds if we can optimize, too *)
968              if Checker.checkIR(optimized) then          if Checker.checkIR(optimized) then printErr "Compilation succeeded." else ();
969               printErr "Compilation succeeded." (* Note: it only succeeds if we can optimize, too *)  
             else  
              ();  
970              optimized              optimized
971            end (* compile *)            end (* compile *)
972    

Legend:
Removed from v.1008  
changed lines
  Added in v.1152

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0