Skip to content

Instantly share code, notes, and snippets.

@paulkaplan
Created January 29, 2013 06:50
Show Gist options
  • Save paulkaplan/4662331 to your computer and use it in GitHub Desktop.
Save paulkaplan/4662331 to your computer and use it in GitHub Desktop.
Scene writer for POVRay, with a simple ruby API
class Scene
attr_accessor :lights, :objects, :camera
def initialize
@lights = []
@objects = []
end
def add_light light
@lights.push light
end
def add_object object
@objects.push object
end
def to_inc filename="out.inc"
f = File.open( filename, "r+")
objects.each do |o|
f.print o.to_s
end
lights.each do |l|
f.print l.to_s
end
end
end
class Light
attr_accessor :position, :color
def initialize pos, color
@position= pos
@color = color
end
def to_s
"light_source { #{position.to_s} #{color.to_s} }"
end
end
class Object3D
attr_accessor :texture, :rotate, :translate, :scale
def initialize
@translate = Vector3.new(0, 0, 0)
@scale = Vector3.new(0, 0, 0)
@rotate = Vector3.new(0, 0, 0)
end
def to_s out
out << " translate #{@translate.to_s} "
out << " rotate #{@rotate.to_s} "
out << " scale #{@scale.to_s} "
end
end
class Plane < Object3D
attr_accessor :normal, :distance
def initialize normal, distance
super()
@normal = normal
@distance = distance
end
def to_s
out = "object {"
out << " plane { #{@normal.to_s}, #{@distance} }"
out = super(out)
out << " texture { pigment { color White } }"
out << "}"
end
end
class Mesh < Object3D
attr_accessor :triangles
def initialize infile
super()
solid = File.open(infile).read
matches = solid.scan /vertex\s+([-+]?\d+\.\d+[eE][-+]?[0-9]+)\s+([-+]?\d+\.\d+[eE][-+]?[0-9]+)\s+([-+]?\d+\.\d+[eE][-+]?[0-9]+)?/
@triangles = matches.map {|x| [Float(x[0]), Float(x[1]), Float(x[2])] }
end
def to_s
out = "object {"
out << "mesh {"
triangles.each_slice(3) do |tri|
out << "triangle {"
tri.each do |vertex|
out << vertex_to_s(vertex)
out << ", " unless vertex == tri.last
end
out << "}\n"
end
out << "}\n"
out << "texture { Surface_Texture }"
out = super(out)
out << "}"
end
end
class Texture
end
def vertex_to_s(vertex)
"\t<#{vertex[0]}, #{vertex[1]}, #{vertex[2]}>"
end
class Vector3
attr_accessor :x, :y, :z
def initialize x, y, z
@x = x
@y = y
@z = z
end
def to_s
" <#{@x}, #{@y}, #{@z}> "
end
end
class Color
attr_accessor :r, :g, :b
def initialize r, g, b
@r = r
@g = g
@b = b
end
def to_s
"color <#{r}, #{g}, #{b}>"
end
end
class Camera
end
#### Test #####
a = Scene.new
a.add_object Mesh.new("dolos.stl")
a.add_object Plane.new( Vector3.new(0, 1, 0), 0)
a.add_light Light.new( Vector3.new(-5, 5, 5), Color.new(1, 0, 0) )
a.objects[0].scale = Vector3.new(1.25, 1.25,1.25)
a.to_inc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment