From e2236959140faa1a8e2d5fc7a7876e3b3de58992 Mon Sep 17 00:00:00 2001 From: Thomas FORGIONE Date: Tue, 22 Nov 2016 12:09:54 +0100 Subject: [PATCH] Added bounding box and scaling options --- .gitignore | 3 +++ conv3d/model.py | 54 +++++++++++++++++++++++++++++++++++++++++++++++++ modelviewer.py | 2 +- 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6a2bf47..d1d4a92 100644 --- a/.gitignore +++ b/.gitignore @@ -88,3 +88,6 @@ ENV/ # Rope project settings .ropeproject + +# Models +examples diff --git a/conv3d/model.py b/conv3d/model.py index c154c01..a1c4b4d 100644 --- a/conv3d/model.py +++ b/conv3d/model.py @@ -48,9 +48,12 @@ class ModelParser: self.normals = [] self.tex_coords = [] self.faces = [] + self.bounding_box = BoundingBox() + self.center_and_scale = True def add_vertex(self, vertex): self.vertices.append(vertex) + self.bounding_box.add(vertex) def add_tex_coord(self, tex_coord): self.tex_coords.append(tex_coord) @@ -75,6 +78,14 @@ class ModelParser: import OpenGL.GL as gl gl.glColor3f(1.0,0.0,0.0) + + if self.center_and_scale: + center = self.bounding_box.get_center() + scale = self.bounding_box.get_scale() / 2 + gl.glPushMatrix() + gl.glScalef(1/scale, 1/scale, 1/scale) + gl.glTranslatef(-center.x, -center.y, -center.z) + gl.glBegin(gl.GL_TRIANGLES) for face in self.faces: v1 = self.vertices[face.a.vertex] @@ -85,6 +96,49 @@ class ModelParser: gl.glVertex3f(v3.x, v3.y, v3.z) gl.glEnd() + if self.center_and_scale: + gl.glPopMatrix() + +class BoundingBox: + def __init__(self): + self.min_x = +float('inf') + self.min_y = +float('inf') + self.min_z = +float('inf') + + self.max_x = -float('inf') + self.max_y = -float('inf') + self.max_z = -float('inf') + + def add(self, vertex): + self.min_x = min(self.min_x, vertex.x) + self.min_y = min(self.min_y, vertex.y) + self.min_z = min(self.min_z, vertex.z) + + self.max_x = max(self.max_x, vertex.x) + self.max_y = max(self.max_y, vertex.y) + self.max_z = max(self.max_z, vertex.z) + + def __str__(self): + return "[{},{}],[{},{}],[{},{}]".format( + self.min_x, + self.min_y, + self.min_z, + self.max_x, + self.max_y, + self.max_z) + + def get_center(self): + return Vertex( + (self.min_x + self.max_x) / 2, + (self.min_y + self.max_y) / 2, + (self.min_z + self.max_z) / 2) + + def get_scale(self): + return max( + abs(self.max_x - self.min_x), + abs(self.max_y - self.min_y), + abs(self.max_z - self.min_z)) + class Exporter: def __init__(self, model): diff --git a/modelviewer.py b/modelviewer.py index 5f0440c..b74d31d 100755 --- a/modelviewer.py +++ b/modelviewer.py @@ -45,7 +45,7 @@ def main(args = {}): running = True - model = load_model('./examples/cube.obj') + model = load_model('./examples/link.obj') while running: for event in pygame.event.get():