Commit c901eec2 authored by sumpfralle's avatar sumpfralle

fixed code-style issues


git-svn-id: https://pycam.svn.sourceforge.net/svnroot/pycam/trunk@501 bbaffbd6-741e-11dd-a85d-61de82d9cad9
parent c9ae4ffc
......@@ -36,15 +36,23 @@ BUTTON_ROTATE = gtk.gdk.BUTTON1_MASK
BUTTON_MOVE = gtk.gdk.BUTTON2_MASK
BUTTON_ZOOM = gtk.gdk.BUTTON3_MASK
# the length of the distance vector does not matter - it will be normalized and multiplied later anyway
# The length of the distance vector does not matter - it will be normalized and
# multiplied later anyway.
VIEWS = {
"reset": {"distance": (1.0, 1.0, 1.0), "center": (0.0, 0.0, 0.0), "up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"top": {"distance": (0.0, 0.0, 1.0), "center": (0.0, 0.0, 0.0), "up": (0.0, 1.0, 0.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"bottom": {"distance": (0.0, 0.0, -1.0), "center": (0.0, 0.0, 0.0), "up": (0.0, 1.0, 0.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"left": {"distance": (-1.0, 0.0, 0.0), "center": (0.0, 0.0, 0.0), "up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"right": {"distance": (1.0, 0.0, 0.0), "center": (0.0, 0.0, 0.0), "up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"front": {"distance": (0.0, -1.0, 0.0), "center": (0.0, 0.0, 0.0), "up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"back": {"distance": (0.0, 1.0, 0.0), "center": (0.0, 0.0, 0.0), "up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"reset": {"distance": (1.0, 1.0, 1.0), "center": (0.0, 0.0, 0.0),
"up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"top": {"distance": (0.0, 0.0, 1.0), "center": (0.0, 0.0, 0.0),
"up": (0.0, 1.0, 0.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"bottom": {"distance": (0.0, 0.0, -1.0), "center": (0.0, 0.0, 0.0),
"up": (0.0, 1.0, 0.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"left": {"distance": (-1.0, 0.0, 0.0), "center": (0.0, 0.0, 0.0),
"up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"right": {"distance": (1.0, 0.0, 0.0), "center": (0.0, 0.0, 0.0),
"up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"front": {"distance": (0.0, -1.0, 0.0), "center": (0.0, 0.0, 0.0),
"up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
"back": {"distance": (0.0, 1.0, 0.0), "center": (0.0, 0.0, 0.0),
"up": (0.0, 0.0, 1.0), "znear": 0.1, "zfar": 1000.0, "fovy": 30.0},
}
......@@ -70,7 +78,9 @@ class Camera:
def center_view(self):
s = self.settings
# center the view on the object
self.view["center"] = ((s.get("maxx") + s.get("minx"))/2, (s.get("maxy") + s.get("miny"))/2, (s.get("maxz") + s.get("minz"))/2)
self.view["center"] = ((s.get("maxx") + s.get("minx")) / 2,
(s.get("maxy") + s.get("miny")) / 2,
(s.get("maxz") + s.get("minz")) / 2)
def auto_adjust_distance(self):
s = self.settings
......@@ -80,19 +90,21 @@ class Camera:
dimy = s.get("maxy") - s.get("miny")
dimz = s.get("maxz") - s.get("minz")
max_dim = max(max(dimx, dimy), dimz)
width, height = self._get_screen_dimensions()
win_size = min(width, height)
distv = Point(v["distance"][0], v["distance"][1], v["distance"][2]).normalize()
# the multiplier "2.0" is based on: sqrt(2) + margin -- the squre root makes sure, that the the diagonal fits
distv = Point(v["distance"][0], v["distance"][1],
v["distance"][2]).normalize()
# The multiplier "2.0" is based on: sqrt(2) + margin -- the squre root
# makes sure, that the the diagonal fits.
distv = distv.mul((max_dim * 2.0) / math.sin(v["fovy"]/2))
self.view["distance"] = (distv.x, distv.y, distv.z)
# adjust the "far" distance for the camera to make sure, that huge models (e.g. x=1000) are still visible
# Adjust the "far" distance for the camera to make sure, that huge
# models (e.g. x=1000) are still visible.
self.view["zfar"] = 100 * max_dim
def scale_distance(self, scale):
if scale != 0:
dist = self.view["distance"]
self.view["distance"] = (scale * dist[0], scale * dist[1], scale * dist[2])
self.view["distance"] = (scale * dist[0], scale * dist[1],
scale * dist[2])
def get(self, key, default=None):
if (not self.view is None) and self.view.has_key(key):
......@@ -110,7 +122,8 @@ class Camera:
@type y_move: int
@value y_move: movement of the mouse along the y axis
@type max_model_shift: float
@value max_model_shift: maximum shifting of the model view (e.g. for x_move == screen width)
@value max_model_shift: maximum shifting of the model view (e.g. for
x_move == screen width)
"""
factors_x, factors_y = self._get_axes_vectors()
width, height = self._get_screen_dimensions()
......@@ -128,19 +141,22 @@ class Camera:
old_center = self.view["center"]
new_center = []
for i in range(3):
new_center.append(old_center[i] + max_model_shift * (win_x_rel * factors_x[i] + win_y_rel * factors_y[i]))
new_center.append(old_center[i] + max_model_shift \
* (win_x_rel * factors_x[i] + win_y_rel * factors_y[i]))
self.view["center"] = tuple(new_center)
def rotate_camera_by_screen(self, start_x, start_y, end_x, end_y):
factors_x, factors_y = self._get_axes_vectors()
width, height = self._get_screen_dimensions()
# calculate rotation factors - based on the distance to the center (between -1 and 1)
# calculate rotation factors - based on the distance to the center
# (between -1 and 1)
rot_x_factor = (2.0 * start_x) / width - 1
rot_y_factor = (2.0 * start_y) / height - 1
# calculate rotation angles (between -90 and +90 degrees)
xdiff = end_x - start_x
ydiff = end_y - start_y
# compensate inverse rotation left/right side (around x axis) and top/bottom (around y axis)
# compensate inverse rotation left/right side (around x axis) and
# top/bottom (around y axis)
if rot_x_factor < 0:
ydiff = -ydiff
if rot_y_factor > 0:
......@@ -150,11 +166,14 @@ class Camera:
# rotate around the "up" vector with the y-axis rotation
original_distance = self.view["distance"]
original_up = self.view["up"]
y_rot_matrix = Matrix.get_rotation_matrix_axis_angle(factors_y, rot_y_angle)
new_distance = Matrix.multiply_vector_matrix(original_distance, y_rot_matrix)
y_rot_matrix = Matrix.get_rotation_matrix_axis_angle(factors_y,
rot_y_angle)
new_distance = Matrix.multiply_vector_matrix(original_distance,
y_rot_matrix)
new_up = Matrix.multiply_vector_matrix(original_up, y_rot_matrix)
# rotate around the cross vector with the x-axis rotation
x_rot_matrix = Matrix.get_rotation_matrix_axis_angle(factors_x, rot_x_angle)
x_rot_matrix = Matrix.get_rotation_matrix_axis_angle(factors_x,
rot_x_angle)
new_distance = Matrix.multiply_vector_matrix(new_distance, x_rot_matrix)
new_up = Matrix.multiply_vector_matrix(new_up, x_rot_matrix)
self.view["distance"] = new_distance
......@@ -172,13 +191,17 @@ class Camera:
light_pos[0] = 2 * model.maxx - model.minx
light_pos[1] = 2 * model.maxy - model.miny
light_pos[2] = 2 * model.maxz - model.minz
GL.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, (light_pos[0], light_pos[1], light_pos[2], 1.0))
GL.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, (light_pos[0], light_pos[1],
light_pos[2], 1.0))
# position the camera
camera_position = (v["center"][0] + v["distance"][0],
v["center"][1] + v["distance"][1], v["center"][2] + v["distance"][2])
GLU.gluPerspective(v["fovy"], (0.0 + width) / height, v["znear"], v["zfar"])
GLU.gluLookAt(camera_position[0], camera_position[1], camera_position[2],
v["center"][0], v["center"][1], v["center"][2], v["up"][0], v["up"][1], v["up"][2])
v["center"][1] + v["distance"][1],
v["center"][2] + v["distance"][2])
GLU.gluPerspective(v["fovy"], (0.0 + width) / height, v["znear"],
v["zfar"])
GLU.gluLookAt(camera_position[0], camera_position[1],
camera_position[2], v["center"][0], v["center"][1],
v["center"][2], v["up"][0], v["up"][1], v["up"][2])
GL.glMatrixMode(prev_mode)
def _get_screen_dimensions(self):
......@@ -186,10 +209,12 @@ class Camera:
def _get_axes_vectors(self):
"""calculate the model vectors along the screen's x and y axes"""
# the "up" vector defines, in what proportion each axis of the model is in line with the screen's y axis
# The "up" vector defines, in what proportion each axis of the model is
# in line with the screen's y axis.
v_up = self.view["up"]
factors_y = (v_up[0], v_up[1], v_up[2])
# calculate the proportion of each model axis according to the x axis of the screen
# Calculate the proportion of each model axis according to the x axis of
# the screen.
distv = self.view["distance"]
distv = Point(distv[0], distv[1], distv[2]).normalize()
factors_x = distv.cross(Point(v_up[0], v_up[1], v_up[2])).normalize()
......@@ -224,19 +249,28 @@ class ModelViewWindowGL:
self._position = self.gui.get_object("ProjectWindow").get_position()
self._position = (self._position[0] + 100, self._position[1] + 100)
self.container = self.gui.get_object("view3dbox")
self.gui.get_object("Reset View").connect("clicked", self.rotate_view, VIEWS["reset"])
self.gui.get_object("Left View").connect("clicked", self.rotate_view, VIEWS["left"])
self.gui.get_object("Right View").connect("clicked", self.rotate_view, VIEWS["right"])
self.gui.get_object("Front View").connect("clicked", self.rotate_view, VIEWS["front"])
self.gui.get_object("Back View").connect("clicked", self.rotate_view, VIEWS["back"])
self.gui.get_object("Top View").connect("clicked", self.rotate_view, VIEWS["top"])
self.gui.get_object("Bottom View").connect("clicked", self.rotate_view, VIEWS["bottom"])
self.gui.get_object("Reset View").connect("clicked", self.rotate_view,
VIEWS["reset"])
self.gui.get_object("Left View").connect("clicked", self.rotate_view,
VIEWS["left"])
self.gui.get_object("Right View").connect("clicked", self.rotate_view,
VIEWS["right"])
self.gui.get_object("Front View").connect("clicked", self.rotate_view,
VIEWS["front"])
self.gui.get_object("Back View").connect("clicked", self.rotate_view,
VIEWS["back"])
self.gui.get_object("Top View").connect("clicked", self.rotate_view,
VIEWS["top"])
self.gui.get_object("Bottom View").connect("clicked", self.rotate_view,
VIEWS["bottom"])
# key binding
self.window.connect("key-press-event", self.key_handler)
# OpenGL stuff
glconfig = gtk.gdkgl.Config(mode=gtk.gdkgl.MODE_RGB|gtk.gdkgl.MODE_DEPTH|gtk.gdkgl.MODE_DOUBLE)
glconfig = gtk.gdkgl.Config(mode=gtk.gdkgl.MODE_RGB \
| gtk.gdkgl.MODE_DEPTH | gtk.gdkgl.MODE_DOUBLE)
self.area = gtk.gtkgl.DrawingArea(glconfig)
# first run; might also be important when doing other fancy gtk/gdk stuff
# first run; might also be important when doing other fancy
# gtk/gdk stuff
self.area.connect_after('realize', self.paint)
# called when a part of the screen is uncovered
self.area.connect('expose-event', self.paint)
......@@ -248,13 +282,18 @@ class ModelViewWindowGL:
self.area.connect('motion-notify-event', self.mouse_handler)
self.area.show()
self.container.add(self.area)
self.camera = Camera(self.settings, lambda: (self.area.allocation.width, self.area.allocation.height))
# color the dimension value according to the axes
# for "y" axis: 100% green is too bright on light background - we reduce it a bit
self.camera = Camera(self.settings, lambda: (self.area.allocation.width,
self.area.allocation.height))
# Color the dimension value according to the axes.
# For "y" axis: 100% green is too bright on light background - we
# reduce it a bit.
for color, names in (
(pango.AttrForeground(65535, 0, 0, 0, 100), ("model_dim_x_label", "model_dim_x")),
(pango.AttrForeground(0, 50000, 0, 0, 100), ("model_dim_y_label", "model_dim_y")),
(pango.AttrForeground(0, 0, 65535, 0, 100), ("model_dim_z_label", "model_dim_z"))):
(pango.AttrForeground(65535, 0, 0, 0, 100),
("model_dim_x_label", "model_dim_x")),
(pango.AttrForeground(0, 50000, 0, 0, 100),
("model_dim_y_label", "model_dim_y")),
(pango.AttrForeground(0, 0, 65535, 0, 100),
("model_dim_z_label", "model_dim_z"))):
attributes = pango.AttrList()
attributes.insert(color)
for name in names:
......@@ -343,8 +382,10 @@ class ModelViewWindowGL:
GL.glDepthMask(GL.GL_TRUE)
GL.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST)
GL.glMatrixMode(GL.GL_MODELVIEW)
#GL.glMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, (0.1, 0.1, 0.1, 1.0))
GL.glMaterial(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, (0.1, 0.1, 0.1, 1.0))
#GL.glMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT,
# (0.1, 0.1, 0.1, 1.0))
GL.glMaterial(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR,
(0.1, 0.1, 0.1, 1.0))
#GL.glMaterial(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, (0.5))
if self.settings.get("view_polygon"):
GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL)
......@@ -354,11 +395,15 @@ class ModelViewWindowGL:
GL.glLoadIdentity()
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GL.glViewport(0, 0, self.area.allocation.width, self.area.allocation.height)
GL.glViewport(0, 0, self.area.allocation.width,
self.area.allocation.height)
# lightning
GL.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, (0.3, 0.3, 0.3, 3.)) # Setup The Ambient Light
GL.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, (1., 1., 1., .0)) # Setup The Diffuse Light
GL.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, (.3, .3, .3, 1.0)) # Setup The SpecularLight
# Setup The Ambient Light
GL.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, (0.3, 0.3, 0.3, 3.))
# Setup The Diffuse Light
GL.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, (1., 1., 1., .0))
# Setup The SpecularLight
GL.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, (.3, .3, .3, 1.0))
GL.glEnable(GL.GL_LIGHT0)
# Enable Light One
if self.settings.get("view_light"):
......@@ -366,9 +411,9 @@ class ModelViewWindowGL:
else:
GL.glDisable(GL.GL_LIGHTING)
GL.glEnable(GL.GL_NORMALIZE)
GL.glColorMaterial(GL.GL_FRONT_AND_BACK,GL.GL_AMBIENT_AND_DIFFUSE)
#GL.glColorMaterial(GL.GL_FRONT_AND_BACK,GL.GL_SPECULAR)
#GL.glColorMaterial(GL.GL_FRONT_AND_BACK,GL.GL_EMISSION)
GL.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE)
#GL.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR)
#GL.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_EMISSION)
GL.glEnable(GL.GL_COLOR_MATERIAL)
def destroy(self, widget=None, data=None):
......@@ -379,10 +424,10 @@ class ModelViewWindowGL:
def gtkgl_functionwrapper(function):
def gtkgl_functionwrapper_function(self, *args, **kwords):
gldrawable=self.area.get_gl_drawable()
gldrawable = self.area.get_gl_drawable()
if not gldrawable:
return
glcontext=self.area.get_gl_context()
glcontext = self.area.get_gl_context()
if not gldrawable.gl_begin(glcontext):
return
if not self.initialized:
......@@ -399,11 +444,13 @@ class ModelViewWindowGL:
last_timestamp = self.mouse["timestamp"]
x, y, state = event.x, event.y, event.state
if self.mouse["button"] is None:
if (state == BUTTON_ZOOM) or (state == BUTTON_ROTATE) or (state == BUTTON_MOVE):
if (state == BUTTON_ZOOM) or (state == BUTTON_ROTATE) \
or (state == BUTTON_MOVE):
self.mouse["button"] = state
self.mouse["start_pos"] = [x, y]
else:
# not more than 25 frames per second (enough for decent visualization)
# not more than 25 frames per second (enough for a decent
# visualization)
if time.time() - last_timestamp < 0.04:
return
# a button was pressed before
......@@ -411,7 +458,8 @@ class ModelViewWindowGL:
# the start button is still active: update the view
start_x, start_y = self.mouse["start_pos"]
self.mouse["start_pos"] = [x, y]
# move the mouse from lower left to top right corner for scale up
# Move the mouse from lower left to top right corner for
# scaling up.
scale = 1 - 0.01 * ((x - start_x) + (start_y - y))
# do some sanity checks, scale no more than
# 1:100 on any given click+drag
......@@ -421,17 +469,23 @@ class ModelViewWindowGL:
scale = 100
self.camera.scale_distance(scale)
self._paint_ignore_busy()
elif (state == self.mouse["button"] == BUTTON_MOVE) or (state == self.mouse["button"] == BUTTON_ROTATE):
elif (state == self.mouse["button"] == BUTTON_MOVE) \
or (state == self.mouse["button"] == BUTTON_ROTATE):
start_x, start_y = self.mouse["start_pos"]
self.mouse["start_pos"] = [x, y]
if (state == BUTTON_MOVE):
# determine the biggest dimension (x/y/z) for moving the screen's center in relation to this value
# Determine the biggest dimension (x/y/z) for moving the
# screen's center in relation to this value.
obj_dim = []
obj_dim.append(self.settings.get("maxx") - self.settings.get("minx"))
obj_dim.append(self.settings.get("maxy") - self.settings.get("miny"))
obj_dim.append(self.settings.get("maxz") - self.settings.get("minz"))
obj_dim.append(self.settings.get("maxx") \
- self.settings.get("minx"))
obj_dim.append(self.settings.get("maxy") \
- self.settings.get("miny"))
obj_dim.append(self.settings.get("maxz") \
- self.settings.get("minz"))
max_dim = max(obj_dim)
self.camera.move_camera_by_screen(x - start_x, y - start_y, max_dim)
self.camera.move_camera_by_screen(x - start_x, y - start_y,
max_dim)
else:
# BUTTON_ROTATE
# update the camera position according to the mouse movement
......@@ -456,7 +510,8 @@ class ModelViewWindowGL:
@gtkgl_functionwrapper
@gtkgl_refresh
def _resize_window(self, widget, data=None):
GL.glViewport(0, 0, self.area.allocation.width, self.area.allocation.height)
GL.glViewport(0, 0, self.area.allocation.width,
self.area.allocation.height)
@check_busy
@gtkgl_functionwrapper
......@@ -481,7 +536,8 @@ class ModelViewWindowGL:
("model_dim_x", s.get("maxx") - s.get("minx")),
("model_dim_y", s.get("maxy") - s.get("miny")),
("model_dim_z", s.get("maxz") - s.get("minz"))):
self.gui.get_object(name).set_text("%.3f %s" % (size, s.get("unit")))
self.gui.get_object(name).set_text("%.3f %s" \
% (size, s.get("unit")))
dimension_bar.show()
else:
dimension_bar.hide()
......@@ -513,7 +569,6 @@ def draw_string(x, y, z, p, s, scale=.01):
GL.glTranslatef(x, y, z)
if p == 'xy':
GL.glRotatef(90, 1, 0, 0)
pass
elif p == 'yz':
GL.glRotatef(90, 0, 1, 0)
GL.glRotatef(90, 0, 0, 1)
......@@ -589,7 +644,8 @@ def draw_complete_model_view(settings):
draw_axes(settings)
# stock model
if settings.get("show_bounding_box"):
draw_bounding_box(float(settings.get("minx")), float(settings.get("miny")),
draw_bounding_box(
float(settings.get("minx")), float(settings.get("miny")),
float(settings.get("minz")), float(settings.get("maxx")),
float(settings.get("maxy")), float(settings.get("maxz")),
settings.get("color_bounding_box"))
......
......@@ -43,7 +43,6 @@ import math
import time
import logging
import datetime
import re
import os
import sys
......@@ -969,7 +968,7 @@ class ProjectGui:
# the "delete-event" issues the additional "event" argument
state = event
if state is None:
state = not self._preferences_window_visible
state = not self._preferences_window_visible
if state:
if self._preferences_window_position:
self.preferences_window.move(*self._preferences_window_position)
......@@ -1358,7 +1357,7 @@ class ProjectGui:
self.model.export(comment=self.get_meta_data()).write(fi)
fi.close()
except IOError, err_msg:
log.error("Failed to save model file")
log.error("Failed to save model file: %s" % err_msg)
else:
self.add_to_recent_file_list(filename)
......@@ -1564,7 +1563,7 @@ class ProjectGui:
out.write(text)
out.close()
except IOError, err_msg:
log.error("Failed to save EMC tool file")
log.error("Failed to save EMC tool file: %s" % err_msg)
else:
self.add_to_recent_file_list(filename)
......@@ -1684,7 +1683,6 @@ class ProjectGui:
return self.gui.get_object("boundary_%s_%s" % ("xyz"[index], side))
# disable each zero-dimension in relative margin mode
if current_type == Bounds.TYPE_RELATIVE_MARGIN:
low, high = current_settings.get_bounds()
model_dims = (self.model.maxx - self.model.minx,
self.model.maxy - self.model.miny,
self.model.maxz - self.model.minz)
......@@ -1799,9 +1797,9 @@ class ProjectGui:
self.gui.get_object(value).set_active(True)
set_path_generator(settings["path_generator"])
# path direction
def set_path_direction(input):
def set_path_direction(direction):
for obj, value in (("PathDirectionX", "x"), ("PathDirectionY", "y"), ("PathDirectionXY", "xy")):
if value == input:
if value == direction:
self.gui.get_object(obj).set_active(True)
return
set_path_direction(settings["path_direction"])
......@@ -1953,12 +1951,9 @@ class ProjectGui:
@gui_activity_guard
def save_task_settings_file(self, widget=None, filename=None):
no_dialog = False
if callable(filename):
filename = filename()
if isinstance(filename, basestring):
no_dialog = True
else:
if not isinstance(filename, basestring):
# we open a dialog
filename = self.get_filename_via_dialog("Save settings to ...",
mode_load=False, type_filter=FILTER_CONFIG)
......@@ -2008,7 +2003,7 @@ class ProjectGui:
@progress_activity_guard
def update_toolpath_simulation(self, widget=None, toolpath=None):
import pycam.Simulation.ODEBlocks
import pycam.Simulation.ODEBlocks as ODEBlocks
# get the currently selected toolpath, if none is give
if toolpath is None:
toolpath_index = self._treeview_get_active_index(self.toolpath_table, self.toolpath)
......@@ -2029,9 +2024,8 @@ class ProjectGui:
/ (bounding_box["maxy"] - bounding_box["miny"])
x_steps = int(math.sqrt(grid_size) * proportion)
y_steps = int(math.sqrt(grid_size) / proportion)
simulation_backend = pycam.Simulation.ODEBlocks.ODEBlocks(
toolpath.get_tool_settings(), toolpath.get_bounding_box(),
x_steps=x_steps, y_steps=y_steps)
simulation_backend = ODEBlocks.ODEBlocks(toolpath.get_tool_settings(),
toolpath.get_bounding_box(), x_steps=x_steps, y_steps=y_steps)
self.settings.set("simulation_object", simulation_backend)
# disable the simulation widget (avoids confusion regarding "cancel")
if not widget is None:
......@@ -2240,10 +2234,10 @@ class ProjectGui:
file_filter.add_pattern(ext)
dialog.add_filter(file_filter)
# add filter for all files
filter = gtk.FileFilter()
filter.set_name("All files")
filter.add_pattern("*")
dialog.add_filter(filter)
ext_filter = gtk.FileFilter()
ext_filter.set_name("All files")
ext_filter.add_pattern("*")
dialog.add_filter(ext_filter)
done = False
while not done:
dialog.set_filter(dialog.list_filters()[0])
......@@ -2343,7 +2337,7 @@ class ProjectGui:
destination.close()
log.info("GCode file successfully written: %s" % str(filename))
except IOError, err_msg:
log.error("Failed to save toolpath file")
log.error("Failed to save toolpath file: %s" % err_msg)
else:
self.add_to_recent_file_list(filename)
......@@ -2367,6 +2361,6 @@ class ProjectGui:
if __name__ == "__main__":
gui = ProjectGui()
if len(sys.argv) > 1:
gui.open(sys.argv[1])
gui.load_model_file(sys.argv[1])
gui.mainloop()
......@@ -37,7 +37,8 @@ def get_config_dirname():
from win32com.shell import shellcon, shell
homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
config_dir = os.path.join(homedir, CONFIG_DIR)
except ImportError: # quick semi-nasty fallback for non-windows/win32com case
except ImportError:
# quick semi-nasty fallback for non-windows/win32com case
homedir = os.path.expanduser("~")
# hide the config directory for unixes
config_dir = os.path.join(homedir, "." + CONFIG_DIR)
......@@ -343,7 +344,8 @@ process: 3
return False
return True
def write_to_file(self, filename, tools=None, processes=None, bounds=None, tasks=None):
def write_to_file(self, filename, tools=None, processes=None, bounds=None,
tasks=None):
text = self.get_config_text(tools, processes, bounds, tasks)
try:
fi = open(filename, "w")
......@@ -398,19 +400,23 @@ process: 3
value_type = self.SETTING_TYPES[key]
raw = value_type == str
try:
value_raw = self.config.get(current_section_name, key, raw=raw)
value_raw = self.config.get(current_section_name, key,
raw=raw)
except ConfigParser.NoOptionError:
try:
value_raw = self.config.get(prefix + self.DEFAULT_SUFFIX, key, raw=raw)
value_raw = self.config.get(
prefix + self.DEFAULT_SUFFIX, key, raw=raw)
except ConfigParser.NoOptionError:
value_raw = None
if not value_raw is None:
try:
if value_type == object:
# try to get the referenced object
value = self._get_category_items(key)[int(value_raw)]
value = self._get_category_items(key)[
int(value_raw)]
elif value_type == bool:
if value_raw.lower() in ("1", "true", "yes", "on"):
if value_raw.lower() in (
"1", "true", "yes", "on"):
value = True
else:
value = False
......@@ -446,7 +452,8 @@ process: 3
else:
return str(value_type(value))
def get_config_text(self, tools=None, processes=None, bounds=None, tasks=None):
def get_config_text(self, tools=None, processes=None, bounds=None,
tasks=None):
def get_dictionary_of_bounds(b):
""" this function should be the inverse operation of
'_get_bounds_instance_from_dict'
......@@ -487,7 +494,7 @@ process: 3
for key in self.CATEGORY_KEYS[type_name]:
try:
values = [item[key] for item in type_list]
except KeyError, err_msg:
except KeyError:
values = None
# check if there are values and if they all have the same value
if values and (values.count(values[0]) == len(values)):
......@@ -590,7 +597,8 @@ class ToolpathSettings:
high = (self.bounds["maxx"], self.bounds["maxy"], self.bounds["maxz"])
return Bounds(Bounds.TYPE_CUSTOM, low, high)
def set_tool(self, index, shape, tool_radius, torus_radius=None, speed=0.0, feedrate=0.0):
def set_tool(self, index, shape, tool_radius, torus_radius=None, speed=0.0,
feedrate=0.0):
self.tool_settings = {"id": index,
"shape": shape,
"tool_radius": tool_radius,
......@@ -668,14 +676,14 @@ class ToolpathSettings:
(self.support_grid, "SupportGrid"),
(self.process_settings, "Process")):
for key, value_type in self.SECTIONS[section].items():
raw_value = config.get(section, key, None)
if raw_value is None:
value_raw = config.get(section, key, None)
if value_raw is None:
continue
elif value_type == bool:
value = value_raw.lower() in ("1", "true", "yes", "on")
else:
try:
value = value_type(raw_value)
value = value_type(value_raw)
except ValueError:
log.warn("Settings: Ignored invalid setting " \
"(%s -> %s): %s" % (section, key, value_raw))
......
......@@ -20,18 +20,17 @@ You should have received a copy of the GNU General Public License
along with PyCAM. If not, see <http://www.gnu.org/licenses/>.
"""
import string
import math
import sys
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import OpenGL.GL as GL
import OpenGL.GLU as GLU
import OpenGL.GLUT as GLUT
from OpenGL.constant import Constant
GLUT_WHEEL_UP=Constant('GLUT_WHEEL_UP',3)
GLUT_WHEEL_DOWN=Constant('GLUT_WHEEL_DOWN',4)
GLUT_WHEEL_UP = Constant('GLUT_WHEEL_UP', 3)
GLUT_WHEEL_DOWN = Constant('GLUT_WHEEL_DOWN', 4)
from pycam.Geometry.utils import *
_DrawCurrentSceneFunc = None
_KeyHandlerFunc = None
......@@ -53,79 +52,95 @@ ydist = -1.0
zdist = -8.0
texture_num = 2
object = 0
light = 1
shade_model = GL_FLAT
polygon_mode = GL_FILL
shade_model = GL.GL_FLAT
polygon_mode = GL.GL_FILL
width = 320
height = 200
# A general OpenGL initialization function. Sets all of the initial parameters.
def InitGL(Width, Height): # We call this right after our OpenGL window is created.
def InitGL(Width, Height):
# We call this right after our OpenGL window is created.
global width, height
width = Width
height = Height
glClearColor(0.0, 0.0, 0.0, 0.0) # This Will Clear The Background Color To Black
glClearDepth(1.0) # Enables Clearing Of The Depth Buffer
glDepthFunc(GL_LESS) # The Type Of Depth Test To Do
glEnable(GL_DEPTH_TEST) # Enables Depth Testing
# glShadeModel(GL_SMOOTH) # Enables Smooth Color Shading
# glShadeModel(GL_FLAT) # Enables Flat Color Shading
glShadeModel(shade_model)
glMatrixMode(GL_PROJECTION)
glLoadIdentity() # Reset The Projection Matrix
# Calculate The Aspect Ratio Of The Window
gluPerspective(60.0, float(Width)/float(Height), 0.1, 100.0)
glLightfv(GL_LIGHT0, GL_AMBIENT, (0.5, 0.5, 0.5, 1.0)) # Setup The Ambient Light
glLightfv(GL_LIGHT0, GL_DIFFUSE, (1.0, 1.0, 1.0, 1.0)) # Setup The Diffuse Light
glLightfv(GL_LIGHT0, GL_POSITION, (-10.0, 0.0, 0.0, 1.0)) # Position The Light
glEnable(GL_LIGHT0) # Enable Light One
glMatrixMode(GL_MODELVIEW)
glMaterial(GL_FRONT_AND_BACK, GL_SPECULAR, (0.1, 0.1, 0.1, 1.0))
# glMaterial(GL_FRONT_AND_BACK, GL_SHININESS, (0.5))
glPolygonMode(GL_FRONT_AND_BACK, polygon_mode)
# This Will Clear The Background Color To Black
GL.glClearColor(0.0, 0.0, 0.0, 0.0)
# Enables Clearing Of The Depth Buffer
GL.glClearDepth(1.0)
# The Type Of Depth Test To Do
GL.glDepthFunc(GL.GL_LESS)
# Enables Depth Testing
GL.glEnable(GL.GL_DEPTH_TEST)
# Enables Smooth Color Shading
# GL.glShadeModel(GL.GL_SMOOTH)
# Enables Flat Color Shading
# GL.glShadeModel(GL.GL_FLAT)
GL.glShadeModel(shade_model)
GL.glMatrixMode(GL.GL_PROJECTION)
# Reset The Projection Matrix
GL.glLoadIdentity()
# Calculate The Aspect Ratio Of The Window
GLU.gluPerspective(60.0, float(Width)/float(Height), 0.1, 100.0)
# Setup The Ambient Light
GL.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, (0.5, 0.5, 0.5, 1.0))
# Setup The Diffuse Light
GL.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, (1.0, 1.0, 1.0, 1.0))
# Position The Light
GL.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, (-10.0, 0.0, 0.0, 1.0))
# Enable Light One
GL.glEnable(GL.GL_LIGHT0)
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glMaterial(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, (0.1, 0.1, 0.1, 1.0))
# GL.glMaterial(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, (0.5))
GL.glPolygonMode(GL.GL_FRONT_AND_BACK, polygon_mode)
def ReSizeGLScene(Width, Height):
if Height == 0: # Prevent A Divide By Zero If The Window Is Too Small
# Prevent A Divide By Zero If The Window Is Too Small
if Height == 0:
Height = 1
global width, height
width = Width
height = Height
glViewport(0, 0, Width, Height) # Reset The Current Viewport And Perspective Transformation
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, float(Width)/float(Height), 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
# Reset The Current Viewport And Perspective Transformation
GL.glViewport(0, 0, Width, Height)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GLU.gluPerspective(60.0, float(Width)/float(Height), 0.1, 100.0)
GL.glMatrixMode(GL.GL_MODELVIEW)
# The main drawing function.
def DrawGLScene():
global xrot, yrot, zrot, scale, xdist, ydist, zdist, light
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Clear The Screen And The Depth Buffer
glLoadIdentity() # Reset The View
glTranslatef(xdist,ydist,zdist) # Move Into The Screen
# Clear The Screen And The Depth Buffer
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
GL.glLoadIdentity() # Reset The View
GL.glTranslatef(xdist, ydist, zdist) # Move Into The Screen
glRotatef(xrot,1.0,0.0,0.0) # Rotate The Cube On It's X Axis
glRotatef(yrot,0.0,1.0,0.0) # Rotate The Cube On It's Y Axis
glRotatef(zrot,0.0,0.0,1.0) # Rotate The Cube On It's Z Axis
glScalef(scale,scale,scale)
GL.glRotatef(xrot, 1.0, 0.0, 0.0) # Rotate The Cube On It's X Axis
GL.glRotatef(yrot, 0.0, 1.0, 0.0) # Rotate The Cube On It's Y Axis
GL.glRotatef(zrot, 0.0, 0.0, 1.0) # Rotate The Cube On It's Z Axis
GL.glScalef(scale, scale, scale)
if light:
glEnable(GL_LIGHTING)
GL.glEnable(GL.GL_LIGHTING)
else:
glDisable(GL_LIGHTING)
GL.glDisable(GL.GL_LIGHTING)
if _DrawCurrentSceneFunc:
_DrawCurrentSceneFunc()
# since this is double buffered, swap the buffers to display what just got drawn.
glutSwapBuffers()
# Since this is double buffered, swap the buffers to display what just got
# drawn.
GLUT.glutSwapBuffers()
# The function called whenever a key is pressed
def keyPressed(key, x, y):
......@@ -133,66 +148,66 @@ def keyPressed(key, x, y):
global xrot, yrot, zrot
global _KeyHandlerFunc
key = string.upper(key)
if key == ESCAPE or key=='Q':
key = key.upper()
if (key == ESCAPE) or (key == 'Q'):
# If escape is pressed, kill everything.
sys.exit()
elif key == 'S':
light = not light
elif key == '=':
print "rot=<%g,%g,%g>" % (xrot,yrot,zrot)
print "rot=<%g,%g,%g>" % (xrot, yrot, zrot)
elif key == 'I':
xrot = 110
yrot = 180
zrot = 250
elif key == 'T': # top
xrot=0
yrot=0
zrot=0
xrot = 0
yrot = 0
zrot = 0
elif key == 'F': # front
xrot=-90
yrot=0
zrot=0
xrot = -90
yrot = 0
zrot = 0
elif key == 'R': # right
xrot=-90
yrot=0
zrot=-90
xrot = -90
yrot = 0
zrot = -90
elif key == 'L': # left
xrot=-90
yrot=0
zrot=+90
xrot = -90
yrot = 0
zrot = +90
elif key == 'M':
if shade_model == GL_SMOOTH:
shade_model = GL_FLAT
if shade_model == GL.GL_SMOOTH:
shade_model = GL.GL_FLAT
else:
shade_model = GL_SMOOTH
glShadeModel(shade_model)
shade_model = GL.GL_SMOOTH
GL.glShadeModel(shade_model)
elif key == 'P':
if polygon_mode == GL_FILL:
polygon_mode = GL_LINE
if polygon_mode == GL.GL_FILL:
polygon_mode = GL.GL_LINE
else:
polygon_mode = GL_FILL
glPolygonMode(GL_FRONT_AND_BACK, polygon_mode)
polygon_mode = GL.GL_FILL
GL.glPolygonMode(GL.GL_FRONT_AND_BACK, polygon_mode)
elif _KeyHandlerFunc:
_KeyHandlerFunc(key, x, y)
class mouseState:
button = None
state = None
x=0
y=0
x = 0
y = 0
def mousePressed(button, state, x, y):
global xrot, yrot, zrot, xdist, ydist, zdist, scale
if button==GLUT_WHEEL_DOWN:
if button == GLUT_WHEEL_DOWN:
scale *= 1.1
elif button==GLUT_WHEEL_UP:
elif button == GLUT_WHEEL_UP:
scale /= 1.1
mouseState.button = button
mouseState.state = state
mouseState.x=float(x)
mouseState.y=float(y)
mouseState.x = float(x)
mouseState.y = float(y)
def mouseMoved(x, y):
global xrot, yrot, zrot, xdist, ydist, zdist, scale
......@@ -200,36 +215,33 @@ def mouseMoved(x, y):
x = float(x)
y = float(y)
a1 = math.atan2(mouseState.y-height/2.0, mouseState.x-width/2.0)
r1 = math.sqrt(sqr(mouseState.y-height/2.0)+sqr(mouseState.x-width/2.0))
r1 = math.sqrt((mouseState.y - height / 2.0) ** 2 \
+ (mouseState.x - width / 2.0) ** 2)
a2 = math.atan2(y-height/2.0, x-width/2.0)
r2 = math.sqrt(sqr(y-height/2.0)+sqr(x-width/2.0))
da = abs(a2-a1)
dr = 0
if r2>r1:
dr = r1/r2
else:
dr = r2/r1
if mouseState.button == GLUT_LEFT_BUTTON or mouseState.button == GLUT_RIGHT_BUTTON:
r2 = math.sqrt((y - height / 2.0) ** 2 + (x - width / 2.0) ** 2)
if (mouseState.button == GLUT.GLUT_LEFT_BUTTON) \
or (mouseState.button == GLUT.GLUT_RIGHT_BUTTON):
a3 = math.acos(mouseState.x/width-0.5)
a4 = math.acos(x/width-0.5)
zrot = zrot - (a4-a3)*180/math.pi*2
if mouseState.button == GLUT_RIGHT_BUTTON:
if mouseState.button == GLUT.GLUT_RIGHT_BUTTON:
a3 = math.acos(mouseState.y/height-0.5)
a4 = math.acos(y/height-0.5)
if x>width/2.0:
if x > width / 2.0:
yrot = yrot + (a4-a3)*180/math.pi*2
else:
yrot = yrot - (a4-a3)*180/math.pi*2
if mouseState.button == GLUT_LEFT_BUTTON:
if mouseState.button == GLUT.GLUT_LEFT_BUTTON:
a3 = math.acos(mouseState.y/width-0.5)
a4 = math.acos(y/width-0.5)
xrot = xrot - (a4-a3)*180/math.pi*2
mouseState.x=x
mouseState.y=y
mouseState.x = x
mouseState.y = y
def Visualization(title, drawScene=DrawGLScene, width=320, height=200, handleKey=None):
def Visualization(title, drawScene=DrawGLScene, width=320, height=200,
handleKey=None):
global window, _DrawCurrentSceneFunc, _KeyHandlerFunc
glutInit(sys.argv)
GLUT.glutInit(sys.argv)
_DrawCurrentSceneFunc = drawScene
......@@ -241,47 +253,50 @@ def Visualization(title, drawScene=DrawGLScene, width=320, height=200, handleKey
# RGBA color
# Alpha components supported
# Depth buffer
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE \
| GLUT.GLUT_DEPTH)
# get a 640 x 480 window
glutInitWindowSize(640, 480)
GLUT.glutInitWindowSize(640, 480)
# the window starts at the upper left corner of the screen
glutInitWindowPosition(0, 0)
GLUT.glutInitWindowPosition(0, 0)
# Okay, like the C version we retain the window id to use when closing, but for those of you new
# to Python (like myself), remember this assignment would make the variable local and not global
# if it weren't for the global declaration at the start of main.
window = glutCreateWindow(title)
# Okay, like the C version we retain the window id to use when closing, but
# for those of you new to Python (like myself), remember this assignment
# would make the variable local and not global if it weren't for the global
# declaration at the start of main.
window = GLUT.glutCreateWindow(title)
# Register the drawing function with glut, BUT in Python land, at least using PyOpenGL, we need to
# set the function pointer and invoke a function to actually register the callback, otherwise it
# would be very much like the C version of the code.
glutDisplayFunc(DrawGLScene)
# Register the drawing function with glut, BUT in Python land, at least
# using PyOpenGL, we need to set the function pointer and invoke a function
# to actually register the callback, otherwise it would be very much like
# the C version of the code.
GLUT.glutDisplayFunc(DrawGLScene)
# Uncomment this line to get full screen.
# glutFullScreen()
# GLUT.glutFullScreen()
# When we are doing nothing, redraw the scene.
glutIdleFunc(DrawGLScene)
GLUT.glutIdleFunc(DrawGLScene)
# Register the function called when our window is resized.
glutReshapeFunc(ReSizeGLScene)
GLUT.glutReshapeFunc(ReSizeGLScene)
# Register the function called when the keyboard is pressed.
glutKeyboardFunc(keyPressed)
GLUT.glutKeyboardFunc(keyPressed)
# Register the function called when the mouse is pressed.
glutMouseFunc(mousePressed)
GLUT.glutMouseFunc(mousePressed)
# Register the function called when the mouse is pressed.
glutMotionFunc(mouseMoved)
GLUT.glutMotionFunc(mouseMoved)
# Initialize our window.
InitGL(640, 480)
# Start Event Processing Engine
glutMainLoop()
GLUT.glutMainLoop()
test_model = None
......@@ -291,19 +306,19 @@ test_pathlist = None
def DrawTestScene():
global test_model, test_cutter, test_pathlist
if test_model:
glColor4f(1,0.5,0.5,0.1)
GL.glColor4f(1, 0.5, 0.5, 0.1)
test_model.to_OpenGL()
if test_cutter:
glColor3f(0.5,0.5,0.5)
GL.glColor3f(0.5, 0.5, 0.5)
test_cutter.to_OpenGL()
if test_pathlist:
for path in test_pathlist:
glColor3f(0.5,0.5,1)
glBegin(GL_LINE_STRIP)
GL.glColor3f(0.5, 0.5, 1)
GL.glBegin(GL.GL_LINE_STRIP)
for point in path.points:
glVertex3f(point.x, point.y, point.z)
# glVertex3f(point.x, point.y, point.z+1)
glEnd()
GL.glVertex3f(point.x, point.y, point.z)
# GL.glVertex3f(point.x, point.y, point.z+1)
GL.glEnd()
def ShowTestScene(model=None, cutter=None, pathlist=None):
global test_model, test_cutter, test_pathlist
......
......@@ -21,7 +21,8 @@ along with PyCAM. If not, see <http://www.gnu.org/licenses/>.
"""
import pycam.Utils.log
# Tkinter is used for "EmergencyDialog" below - but we will try to import it carefully
# Tkinter is used for "EmergencyDialog" below - but we will try to import it
# carefully.
#import Tkinter
import sys
import os
......@@ -149,13 +150,14 @@ class EmergencyDialog:
import Tkinter
except ImportError:
# tk is not installed
log.warn("Failed to show error dialog due to a missing Tkinter Python package.")
log.warn("Failed to show error dialog due to a missing Tkinter " \
+ "Python package.")
return
try:
root = Tkinter.Tk()
except Tkinter.TclError, err_msg:
log.info("Failed to create error dialog window (%s). " % str(err_msg) \
+ "Probably you are running PyCAM from a terminal.")
log.info(("Failed to create error dialog window (%s). Probably " \
+ "you are running PyCAM from a terminal.") % err_msg)
return
root.title(title)
root.bind("<Return>", self.finish)
......
......@@ -75,7 +75,7 @@ class ODEBlocks:
or (location_start.y > location_end.y):
swap = location_start
location_start = location_end
location_end = location_start
location_end = swap
cutter_body = ode.Body(self.world)
cutter_shape, cutter_position_func = self.cutter.get_shape("ODE")
self.space.add(cutter_shape)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment