-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.scala
234 lines (196 loc) · 7.14 KB
/
parser.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import scala.util.parsing.combinator._
import scala.util.matching.Regex
case class ModelObject(name:String, props:Map[String, Any])
case class Block(env: ModelParsers.Environment, obj: ModelObject)
class UndefinedVariableException(message:String,
cause:Throwable) extends Exception(message, cause) {
def this(message:String) = this(message, null)
def this(cause:Throwable) = this(null, cause)
def this() = this(null, null)
}
object ModelParsers extends RegexParsers {
type Environment = Map[String, Any]
val Sep: Regex = ",?".r
def ident: Parser[String] = """[a-zA-Z_][a-zA-Z_0-9-]*""".r
def integer: Parser[Int] = """-?\d+""".r ^^
{ case n => n.toInt }
def decimal: Parser[Double] = """-?(\d+(\.\d+)?)|(\d*\.\d+)""".r ^^
{ case n => n.toDouble }
def color: Parser[Color] = "#" ~> "[0-9a-fA-F]{1,6}".r ^^
{ case rgb => new Color(Integer.parseInt(rgb, 16)) }
def tup3fpn: Parser[Tuple3[Double, Double, Double]] = {
decimal ~ "," ~ decimal ~ "," ~ decimal ^^
{ case a ~ "," ~ b ~ "," ~ c => (a, b, c) }
}
def point3: Parser[Point3] = "(" ~> tup3fpn <~ ")" ^^
{ case (x, y, z) => new Point3(x, y, z) }
def vector3: Parser[Vector3] = "<" ~> tup3fpn <~ ">" ^^
{ case (x, y, z) => new Vector3(x, y, z) }
def vertex: Parser[Vertex] = point3 ~ "^" ~ vector3 ^^
{ case p ~ "^" ~ v => new Vertex(p, v) }
def value: Parser[Any] = ((decimal ||| integer) |
color | vertex | point3 | vector3 | (block ||| varref))
def valueList: Parser[List[Any]] = "[" ~> repsep(value, Sep) <~ "]"
def property: Parser[Tuple2[String, Any]] = {
ident ~ "=" ~ (value | valueList) ^^
{ case n ~ "=" ~ v => (n, v) }
}
def propertyList: Parser[Map[String, Any]] = {
repsep(property, Sep) ^^ { case plist => Map() ++ plist }
}
def obj: Parser[ModelObject] = {
ident ~ ":" ~ "{" ~ propertyList ~ "}" ^^
{ case name ~ ":" ~ "{" ~ props ~ "}" => new ModelObject(name, props) }
}
def varref = ident
def vardecl: Parser[Tuple2[String, Any]] = {
ident ~ ":=" ~ (value | valueList) ^^
{ case n ~ ":=" ~ v => (n, v) }
}
def vardecls: Parser[Environment] = {
// (repsep(vardecl, Sep) ?) ^^
// { case Some(vardecls) => Map() ++ vardecls
// case None => Map() }
repsep(vardecl, Sep) ^^ { case vardecls => Map() ++ vardecls }
}
def block: Parser[Block] = {
vardecls ~ Sep ~ obj ^^
{ case vardecls ~ _ ~ obj => new Block(vardecls, obj) }
}
}
class ModelEval(val parent:Option[ModelEval], val block:Block) {
val AutoApplyPrefix = "_"
def this(block:Block) = {
this(None, block)
}
def eval(b: Block): Any = {
new ModelEval(Some(this), b).eval()
}
def evalVar(varName: String): Option[Any] = {
try {
Some(evalValue(block.env(varName)))
} catch {
case e: NoSuchElementException => parent match {
case Some(p: ModelEval) => p.evalVar(varName)
case _ => None
}
}
}
def evalValue(value: Any): Any = {
value match {
case s:String => evalVar(s) match {
case Some(s) => s
case None => throw new UndefinedVariableException("Undefined variable!")
}
case l:List[Any] => l map {v => evalValue(v)}
case b:Block => eval(b)
case x => x
}
}
def evalProp(propName: String): Any = {
val property = try {
// First see if the property is defined on the object
block.obj.props(propName)
} catch {
// Try looking for the property in the variables defined
// for the block.
case e:NoSuchElementException =>
try {
evalValue(AutoApplyPrefix + propName)
} catch {
// If the variable lookup fails, throw the original exception
case _: UndefinedVariableException => throw e
}
}
evalValue(property)
}
def evalProps(propNames: String*): Seq[Any] = {
propNames.map(evalProp(_))
}
def eval(): Any = {
block.obj.name match {
case "point-light" =>
evalProps("location", "intensity") match {
case Seq(l:Point3, i:Color) => new PointLight(l, i)
}
case "screen" =>
evalProps("origin", "xAxis", "yAxis", "xRes", "yRes") match {
case Seq(o:Point3, xAxis: Vector3, yAxis: Vector3, xRes: Int, yRes: Int) =>
new Screen(o, xAxis, yAxis, xRes, yRes)
}
case "camera" =>
try {
evalProps("location", "view-angle", "view-vector", "up-vector", "x-res", "y-res") match {
case Seq(l: Point3, a: Double, v: Vector3, u: Vector3, x: Int, y: Int) =>
Camera(l, a, v, u, x, y)
}
} catch {
// FIXME: Narrow down the Exceptions we catch?
case _: Exception => evalProps("eye", "screen") match {
case Seq(e: Point3, s: Screen) => Camera(e, s)
}
}
case "sphere" =>
evalProps("origin", "radius", "material") match {
case Seq(o: Point3, r: Double, m: Material) => new Sphere(o, r, m)
}
case "triangle" =>
evalProps("vertex1", "vertex2", "vertex3", "material") match {
case Seq(v1: Vertex, v2: Vertex, v3: Vertex, m:Material) =>
new Triangle(v1, v2, v3, m)
}
case "material" =>
evalProps("reflectance", "reflectivity", "highlight") match {
case Seq(rc: Color, rv:Color, h: Color) => new GenericMaterial(rc, rv, h)
}
case "model" =>
evalProps("camera", "lights", "surfaces", "ambient",
"bg", "recursion-depth") match {
case Seq(c: Camera, li: List[Light], su: List[Surface], amb: Color,
bg: Color, rd: Int) =>
new Model(c, li, su, amb, bg, rd)
}
}
}
}
object ModelEval {
def eval(block: Block) = new ModelEval(block).eval()
}
object ModelParsersMain {
def main(args: Array[String]) : Unit = {
implicit def asCharSequence(s: String) = s.asInstanceOf[CharSequence]
println(ModelParsers.parseAll(ModelParsers.color, "#abcdef".asInstanceOf[CharSequence]))
println(ModelParsers.parseAll(ModelParsers.point3, "(1,2,3)".asInstanceOf[CharSequence]))
println(ModelParsers.parseAll(ModelParsers.property, "madness = <3.0, 2.0, 1.0>".asInstanceOf[CharSequence]))
println(ModelParsers.parseAll(ModelParsers.vertex, "(1,2,3) ^ <1,2,3>"))
println(ModelParsers.parseAll(ModelParsers.obj, "foo: { bar = 2, baz = #123456 }"))
println(ModelParsers.parseAll(ModelParsers.block, "foo: { bar = 2, baz = #123456 }"))
}
}
object RenderTest {
import java.io._
def badInput(n:String, x: Any) = {
println("Received input other than a " + n)
println(x)
}
def main(args:Array[String]) = {
val inFilename = args(0)
val outFilename = args(1)
val input = new BufferedReader(new FileReader(inFilename))
val output = new File(outFilename)
try {
ModelParsers.parseAll(ModelParsers.block, input).get match {
case (block: Block) => {
ModelEval.eval(block) match {
case model: Model => model.render(output)
case x => badInput("model", x)
}
}
case x => badInput("block", x)
}
} finally {
if (input != null)
input.close()
}
}
}