def resetLights(self): self.lights = [] for i in range(8): light = GD.cfg.get('render/light%d' % i, None) if light is not None: GD.debug(" Add light %s: %s: " % (i,light)) self.lights.append(Light(i,light))
def draw(self,*args,**kargs): clear() GD.debug("Drawing SELECTION: %s" % self.names) self._actors = draw(self.names,clear=False,shrink=self.shrink,*args,**kargs) for i,a in enumerate(self.annotations): if a[1]: self.drawAnnotation(i)
def askConfigPreferences(items, prefix=None, store=None): """Ask preferences stored in config variables. Items in list should only be keys. store is usually a dictionary, but can be any class that allow the setdefault method for lookup while setting the default, and the store[key]=val syntax for setting the value. If a prefix is given, actual keys will be 'prefix/key'. The current values are retrieved from the store, and the type returned will be in accordance. If no store is specified, the global config GD.cfg is used. """ if not store: store = GD.cfg if prefix: items = ["%s/%s" % (prefix, i) for i in items] itemlist = [[i, store.setdefault(i, "")] for i in items] res, accept = widgets.InputDialog(itemlist, "Config Dialog", GD.gui).getResult() if accept: GD.debug(res) if draw.ack("Update the settings?"): # This does not work for our Config class! # store.update(res) # Therefore, set individually for k, v in res.items(): store[k] = v ## for i,r in zip(itemlist,res): ## GD.debug("IN : %s\nOUT: %s" % (i,r)) ## if type(i[1]) == str: ## store[r[0]] = r[1] ## else: ## store[r[0]] = eval(r[1]) GD.debug(GD.cfg) return accept
def askConfigPreferences(items,prefix=None,store=None): """Ask preferences stored in config variables. Items in list should only be keys. store is usually a dictionary, but can be any class that allow the setdefault method for lookup while setting the default, and the store[key]=val syntax for setting the value. If a prefix is given, actual keys will be 'prefix/key'. The current values are retrieved from the store, and the type returned will be in accordance. If no store is specified, the global config GD.cfg is used. """ if not store: store = GD.cfg if prefix: items = [ '%s/%s' % (prefix,i) for i in items ] itemlist = [ [ i,store.setdefault(i,'') ] for i in items ] res,accept = widgets.inputDialog(itemlist,'Config Dialog').process() if accept: for i,r in zip(itemlist,res): GD.debug("IN : %s\nOUT: %s" % (i,r)) if type(i[1]) == str: store[r[0]] = r[1] else: store[r[0]] = eval(r[1]) return accept
def glinit(self,mode=None): if mode: self.rendermode = mode GL.glClearColor(*colors.RGBA(self.bgcolor))# Clear The Background Color GL.glClearDepth(1.0) # Enables Clearing Of The Depth Buffer GL.glDepthFunc(GL.GL_LESS) # The Type Of Depth Test To Do GL.glEnable(GL.GL_DEPTH_TEST) # Enables Depth Testing if self.rendermode == 'wireframe': GL.glShadeModel(GL.GL_FLAT) # Enables Flat Color Shading GL.glDisable(GL.GL_LIGHTING) elif self.rendermode == 'flat': GL.glShadeModel(GL.GL_FLAT) # Enables Flat Color Shading GL.glDisable(GL.GL_LIGHTING) elif self.rendermode == 'smooth': GL.glShadeModel(GL.GL_SMOOTH) # Enables Smooth Color Shading GL.glEnable(GL.GL_LIGHTING) for l,i in zip(['light0','light1'],[GL.GL_LIGHT0,GL.GL_LIGHT1]): key = 'render/%s' % l light = GD.cfg.get(key,self.default_light) GD.debug(" set up %s %s" % (l,light)) GL.glLightModel(GL.GL_LIGHT_MODEL_AMBIENT,rgba(GD.cfg['render/ambient'])) GL.glLightModel(GL.GL_LIGHT_MODEL_TWO_SIDE, GL.GL_TRUE) GL.glLightModel(GL.GL_LIGHT_MODEL_LOCAL_VIEWER, 0) GL.glLightfv(i,GL.GL_AMBIENT,rgba(light['ambient'])) GL.glLightfv(i,GL.GL_DIFFUSE,rgba(light['diffuse'])) GL.glLightfv(i,GL.GL_SPECULAR,rgba(light['specular'])) GL.glLightfv(i,GL.GL_POSITION,rgba(light['position'])) GL.glEnable(i) GL.glMaterialfv(GL.GL_FRONT_AND_BACK,GL.GL_SPECULAR,rgba(GD.cfg['render/specular'])) GL.glMaterialfv(GL.GL_FRONT_AND_BACK,GL.GL_EMISSION,rgba(GD.cfg['render/emission'])) GL.glMaterialfv(GL.GL_FRONT_AND_BACK,GL.GL_SHININESS,GD.cfg['render/shininess']) GL.glColorMaterial(GL.GL_FRONT_AND_BACK,GL.GL_AMBIENT_AND_DIFFUSE) GL.glEnable(GL.GL_COLOR_MATERIAL) else: raise RuntimeError,"Unknown rendering mode"
def setToolbarPlacement(store=None): """Ask placement of toolbars. Items in list should be existing toolbar widgets. """ if store is None: store = GD.cfg toolbar = [GD.gui.modebar, GD.gui.viewbar] setting = ["gui/modebar", "gui/viewbar"] options = [None, "default", "left", "right", "top", "bottom"] label = [str(tb.windowTitle()) for tb in toolbar] current = [store[s] for s in setting] print current itemlist = [(l, options, "select") for (l, c) in zip(label, setting)] itemlist.append(("Store these settings as defaults", False)) res, accept = widgets.InputDialog(itemlist, "Config Dialog", GD.gui).getResult() if accept: GD.debug(res) if res["Store these settings as defaults"]: # The following does not work for our Config class! # store.update(res) # Therefore, we set the items individually for s, l in zip(setting, label): val = res[l] if val == "None": val = None store[s] = val GD.debug(store) return accept
def runScript(self,filename): """Run the specified example.""" self.current = filename selected = os.path.join(self.dir,filename+'.py') GD.debug("Playing script %s" % selected) GD.gui.setcurfile(selected) fileMenu.play()
def start_selection(self,mode,filtr): """Start an interactive picking mode. If selection mode was already started, mode is disregarded and this can be used to change the filter method. """ if self.selection_mode is None: GD.debug("START SELECTION MODE: %s" % mode) self.setMouse(LEFT,self.mouse_pick) self.setMouse(LEFT,self.mouse_pick,SHIFT) self.setMouse(LEFT,self.mouse_pick,CTRL) self.setMouse(RIGHT,self.emit_done) self.setMouse(RIGHT,self.emit_cancel,SHIFT) self.connect(self,DONE,self.accept_selection) self.connect(self,CANCEL,self.cancel_selection) self.setCursor(QtGui.QCursor(QtCore.Qt.CrossCursor)) self.selection_mode = mode self.selection_front = None if filtr == 'none': filtr = None GD.debug("SET SELECTION FILTER: %s" % filtr) self.selection_filter = filtr if filtr is None: self.selection_front = None self.selection.clear() self.selection.setType(self.selection_mode)
def setToolbarPlacement(store=None): """Ask placement of toolbars. Items in list should be existing toolbar widgets. """ if store is None: store = GD.cfg toolbar = [ GD.gui.modebar, GD.gui.viewbar ] setting = ['gui/modebar', 'gui/viewbar' ] options = [ None, 'default', 'left', 'right', 'top', 'bottom' ] label = [ str(tb.windowTitle()) for tb in toolbar ] current = [ store[s] for s in setting ] itemlist = [(l, options[1], 'select', options) for (l,c) in zip(label,setting)] itemlist.append(('Store these settings as defaults', False)) res,accept = widgets.InputDialog(itemlist,'Config Dialog',GD.gui).getResult() if accept: GD.debug(res) if res['Store these settings as defaults']: # The following does not work for our Config class! # store.update(res) # Therefore, we set the items individually for s,l in zip(setting,label): val = res[l] if val == "None": val = None store[s] = val GD.debug(store) return accept
def runApp(args): """Create and run the qt application.""" GD.app = QtGui.QApplication(args) QtCore.QObject.connect(GD.app, QtCore.SIGNAL("lastWindowClosed()"), GD.app, QtCore.SLOT("quit()")) # Set some globals GD.image_formats_qt = map(str, QtGui.QImageWriter.supportedImageFormats()) GD.image_formats_qtr = map(str, QtGui.QImageReader.supportedImageFormats()) if GD.cfg.get("imagesfromeps", False): GD.image_formats_qt = [] if GD.options.debug: print "Qt image types for saving: ", GD.image_formats_qt print "Qt image types for input: ", GD.image_formats_qtr print "gl2ps image types:", GD.image_formats_gl2ps print "image types converted from EPS:", GD.image_formats_fromeps # create GUI, show it, run it windowname = GD.Version count = 0 while windowExists(windowname): if count > 255: print "Can not open the main window --- bailing out" return 1 count += 1 windowname = "%s (%s)" % (GD.Version, count) if GD.cfg.has_key("gui/fontsize"): setFontSize() GD.gui = GUI(windowname, GD.cfg["gui/size"], GD.cfg["gui/pos"]) GD.gui.setcurfile() GD.board = GD.gui.board GD.canvas = GD.gui.canvas GD.gui.show() # Create additional menus (put them in a list to save) menus = [] # History history = GD.cfg["history"] if type(history) == list: m = scriptsMenu.ScriptsMenu("History", files=history, max=10) GD.gui.insertMenu(m) menus.append(m) GD.gui.history = m # Create a menu with pyFormex examples # and insert it before the help menu for title, dir in GD.cfg["scriptdirs"]: m = scriptsMenu.ScriptsMenu(title, dir, autoplay=True) GD.gui.insertMenu(m) menus.append(m) GD.board.write(GD.Version + " (C) B. Verhegghe") # remaining args are interpreted as scripts for arg in args: if os.path.exists(arg): draw.play(arg) GD.app_started = True GD.debug("Using window name %s" % GD.gui.windowTitle()) GD.app.exec_() # store the main window size/pos GD.cfg["history"] = GD.gui.history.files GD.cfg.update({"size": GD.gui.Size(), "pos": GD.gui.Pos()}, name="gui") return 0
def createScriptMenu(scriptdirs,menu,recursive=True): """Create a menu with pyFormex scripts and insert it in specified menu. scriptsdirs is a list of (title,dir) tuples, where title is the menu title and dir is a directory to be scanned for scripts. If recursive is True, subdirectories will be added as a submenu. As a convenience, if an empty dirname is specified and the title is one of the keys in known_scriptdirs, the corresponding dir entry will be used. This enables the user to add pyFormex system script dirs into his config. Returns the list of created menu items. """ menus = [] known_scriptdirs = { 'examples': GD.cfg['examplesdir'] } if len(scriptdirs) > 1: scriptsmenu = widgets.Menu('Scripts',GD.gui.menu) before = GD.gui.menu.item('help').menuAction() GD.gui.menu.insertMenu(before,scriptsmenu) before = None else: scriptsmenu = GD.gui.menu before = scriptsmenu.itemAction('help') for title,dirname in scriptdirs: GD.debug("Loading script dir %s" % dirname) if not dirname: dirname = known_scriptdirs[title.lower()] if os.path.exists(dirname): m = scriptsMenu.ScriptsMenu(title,dirname,autoplay=True) scriptsmenu.insert_menu(m,before) menus.append(m) # Needed to keep m linked to a name return menus
def enable(self): GD.debug(" Enable light %s" % (self.light-GL.GL_LIGHT0)) GL.glLightfv(self.light,GL.GL_POSITION,self.position) GL.glLightfv(self.light,GL.GL_AMBIENT,self.ambient) GL.glLightfv(self.light,GL.GL_DIFFUSE,self.diffuse) GL.glLightfv(self.light,GL.GL_SPECULAR,self.specular) GL.glEnable(self.light)
def runNext(self): try: i = self.files.index(self.current) + 1 except ValueError: i = 0 GD.debug("This is script %s out of %s" % (i,len(self.files))) if i < len(self.files): self.runScript(self.files[i])
def runCommand(cmd, RaiseError=True): """Run a command and raise error if exited with error.""" GD.message("Running command: %s" % cmd) sta, out = commands.getstatusoutput(cmd) if sta != 0 and RaiseError: GD.debug(out) raise RuntimeError, "Error while executing command:\n %s" % cmd return sta, out
def pickDraw(): K = pick() GD.debug("PICKED: %s"%K) if len(K) > 0: undraw(K) GD.debug("DRAWING PICKED: %s"%K) draw(K,color='red',bbox=None) return K
def flyAlong(path,upvector=[0.,1.,0.],sleeptime=0.5): for seg in path: GD.debug("Eye: %s; Center: %s" % (seg[0],seg[1])) GD.canvas.camera.lookAt(seg[0],seg[1],upvector) GD.canvas.display() GD.canvas.update() if multisave and multisave[4]: saveNext() sleep(sleeptime)
def runAllNext(self): """Run the current and all following scripts.""" try: i = self.files.index(self.current) except ValueError: i = 0 GD.debug("Running scripts %s-%s" % (i,len(self.files))) self.runAllFiles(self.files[i:]) GD.debug("Exiting runAllNext")
def accept_selection(self,clear=False): """Cancel an interactive picking mode. If clear == True, the current selection is cleared. """ GD.debug("CANCEL SELECTION MODE") if clear: self.selection.clear() self.selection_canceled = True self.selection_busy = False
def keyPressEvent (self,e): """Top level key press event handler. Events get here if they are not handled by a lower level handler. """ self.emit(QtCore.SIGNAL("Wakeup"),()) if e.key() == QtCore.Qt.Key_F2: GD.debug('F2 pressed!') self.emit(QtCore.SIGNAL("Save"),()) e.ignore()
def insertMenu(self,menu,before='help'): """Insert a menu in the menubar before the specified menu. The new menu can be inserted BEFORE any of the existing menus. By default the new menu will be inserted before the Help menu. """ item = menuItem(self,before) if item: QtGui.QMenuBar.insertMenu(self,item,menu) else: GD.debug("No such menu item: %s" % before)
def runScript(self,filename): """Run the specified script.""" self.current = filename if self.dir: selected = os.path.join(self.dir,filename+'.py') else: selected = filename GD.debug("Playing script %s" % selected) GD.gui.setcurfile(selected) if self.autoplay: draw.play()
def create_list(self,**kargs): self.list = GL.glGenLists(1) GL.glNewList(self.list,GL.GL_COMPILE) ok = False try: self.drawGL(**kargs) ok = True finally: if not ok: GD.debug("Error while creating a display list") GL.glEndList()
def finish_selection(self): """End an interactive picking mode.""" GD.debug("END SELECTION MODE") self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.setMouse(LEFT,self.dynarot) self.setMouse(LEFT,None,SHIFT) self.setMouse(LEFT,None,CTRL) self.setMouse(RIGHT,self.dynazoom) self.setMouse(RIGHT,None,SHIFT) self.disconnect(self,DONE,self.accept_selection) self.disconnect(self,CANCEL,self.cancel_selection) self.selection_mode = None
def named(name): """Returns the global object named name.""" # GD.debug("name %s" % name) if GD.PF.has_key(name): # GD.debug("Found %s in GD.PF" % name) dic = GD.PF elif globals().has_key(name): GD.debug("Found %s in globals()" % name) dic = globals() else: raise NameError, "Name %s is in neither GD.PF nor globals()" % name return dic[name]
def rotateAround(): """Rotate the selection.""" FL = selection.check() if FL: res = askItems([['axis',2],['angle','90.0'],['around','[0.0,0.0,0.0]']]) if res: axis = int(res['axis']) angle = float(res['angle']) around = eval(res['around']) GD.debug('around = %s'%around) selection.changeValues([ F.rotate(angle,axis,around) for F in FL ]) selection.drawChanges()
def flyAlong(path,upvector=[0.,1.,0.],sleeptime=None): for seg in path: GD.debug("Eye: %s; Center: %s" % (seg[0],seg[1])) GD.canvas.camera.lookAt(seg[0],seg[1],upvector) GD.canvas.display() GD.canvas.update() image.saveNext() if sleeptime is None: sleeptime = GD.cfg['draw/flywait'] sleeptime = float(sleeptime) if sleeptime > 0.0: sleep(sleeptime)
def rotateAround(): """Rotate the selection.""" FL = checkSelection() if FL: res = askItems([["axis", 2], ["angle", "90.0"], ["around", "[0.0,0.0,0.0]"]]) if res: axis = int(res["axis"]) angle = float(res["angle"]) around = eval(res["around"]) GD.debug("around = %s" % around) changeSelection([F.rotate(angle, axis, around) for F in FL]) drawChanges()
def exit(all=False): """Exit from the current script or from pyformex if no script running.""" if scriptRunning: if all: raise ExitAll # exit from pyformex else: raise Exit # exit from script only if GD.app and GD.app_started: # exit from GUI GD.debug("draw.exit called while no script running") GD.app.quit() else: # the gui didn't even start sys.exit(0)
def setRenderMode(self,rm): """Set the rendermode. This changes the rendermode and redraws everything with the new mode. """ GD.debug("Changing Render Mode to %s" % rm) if rm != self.rendermode: if rm not in Canvas.rendermodes: rm = Canvas.rendermodes[0] self.rendermode = rm GD.debug("Redrawing with mode %s" % self.rendermode) self.glinit(self.rendermode) self.redrawAll()
def start_selection(self,mode): """Start an interactive picking mode.""" if self.selection_mode is None: GD.debug("START SELECTION MODE: %s" % mode) self.setMouse(LEFT,self.mouse_pick) self.setMouse(LEFT,self.mouse_pick,SHIFT) self.setMouse(LEFT,self.mouse_pick,CTRL) self.setMouse(RIGHT,self.emit_done) self.setMouse(RIGHT,self.emit_cancel,SHIFT) self.connect(self,DONE,self.accept_selection) self.connect(self,CANCEL,self.cancel_selection) self.selection_mode = mode self.front_selection = None self.setCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))