python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ CrossoverSite_Marker.py CrossoverSite_Marker object wraps the functionality of identifying the potential crossoversites between the given DNA segments. It also creates Handles at these crossover sites. The user can then click on a hanle to create that crossover. As of 2008-06-01, instance of this class is being used by MakeCrossovers_GraphicsMode. @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-05-29 - 2008-06-01 : Created Created to support MakeCrossovers command for v1.1.0 TODO 2008-06-01: - This is just an initial implmentation and is subjected to heavy revision. It is created mainly to support the make crossovers command (a 'nice to have' feature for v1.1.0 implemented just a few days before the release). - The search algorithm is slow and needs to be revised. - Works only for PAM3 model - Works reliable only for straight dna segments (curved Dna segments unsupported for now) - Add DOCUMENTATION - Still need to discuss whether this object be better created in GraphicsMode or the Command part - GM looks more appropriate since most of the things are related to displaying things in the GM (But the 'identifying crossover sites' is a general part) """ import foundation.env as env import time from utilities.constants import black, banana from dna.commands.MakeCrossovers.MakeCrossovers_Handle import MakeCrossovers_Handle from geometry.VQT import orthodist, norm, vlen, angleBetween from Numeric import dot from model.bonds import bond_direction from graphics.display_styles.DnaCylinderChunks import get_all_available_dna_base_orientation_indicators from exprs.instance_helpers import get_glpane_InstanceHolder from exprs.Arrow import Arrow from exprs.Highlightable import Highlightable from utilities.prefs_constants import makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key MAX_DISTANCE_BETWEEN_CROSSOVER_SITES = 17 #Following is used by the algoritm that searches for neighboring dna segments #(to a given dnaSegment) to mark crossover sites (atom pairs that will be #involved in a crossover) MAX_PERPENDICULAR_DISTANCE_BET_SEGMENT_AXES = 34 MAX_ANGLE_BET_PLANE_NORMAL_AND_AVG_CENTER_VECTOR_OF_CROSSOVER_PAIRS = 32 class CrossoverSite_Marker: """ CrossoverSite_Marker object wraps the functionality of identifying the potential crossoversites between the given DNA segments. It also creates Handles at these crossover sites. The user can then click on a hanle to create that crossover. As of 2008-06-01, instance of this class is being used by MakeCrossovers_GraphicsMode. @see: MakeCrossovers_GraphicsMode """ def __init__(self, graphicsMode): self.graphicsMode = graphicsMode self.command = self.graphicsMode.command self.win = self.graphicsMode.win self.glpane = self.graphicsMode.glpane self._allDnaSegmentDict = {} self._base_orientation_indicator_dict = {} self._DEBUG_plane_normals_ends_for_drawing = [] self._DEBUG_avg_center_pairs_of_potential_crossovers = [] self.final_crossover_pairs_dict = {} self._final_avg_center_pairs_for_crossovers_dict = {} self._raw_crossover_atoms_dict = {} self.handleDict = {} #This dict contains all ids of all the potential cross over atoms, whose #also have their neighbor atoms in the self._raw_crossover_atoms_dict self._raw_crossover_atoms_with_neighbors_dict = {} self._final_crossover_atoms_dict = {} def update(self): """ Does a full update (including exprs handle creation @see: self.partialUpdate() """ self.clearDictionaries() self._updateAllDnaSegmentDict() ##print "***updating crossover sites", time.clock() self._updateCrossoverSites() ##print "**crossover sites updated", time.clock() ##print "***creating handles", time.clock() self._createExprsHandles() ##print "***%d handles created, new time = %s"%(len(self.handleDict), time.clock()) self.glpane.gl_update() def partialUpdate(self): """ Updates everything but the self.handleDict i.e. updates the crossover sites but doesn't create/ update handles. #DOC and revise @see: MakeCrossovers_GraphicsMode.leftUp() @see: MakeCrossovers_GraphicsMode.leftDrag() @see: self.update() """ self._allDnaSegmentDict = {} self._base_orientation_indicator_dict = {} self._DEBUG_plane_normals_ends_for_drawing = [] self._DEBUG_avg_center_pairs_of_potential_crossovers = [] self.final_crossover_pairs_dict = {} self._final_avg_center_pairs_for_crossovers_dict = {} self._raw_crossover_atoms_dict = {} #This dict contains all ids of all the potential cross over atoms, whose #also have their neighbor atoms in the self._raw_crossover_atoms_dict self._raw_crossover_atoms_with_neighbors_dict = {} self._final_crossover_atoms_dict = {} self._updateAllDnaSegmentDict() self._updateCrossoverSites() def updateHandles(self): """ Only update handles, don't recompute crossover sites. (This method assumes that the crossover sites are up to date. """ self._createExprsHandles() def updateExprsHandleDict(self): self.clearDictionaries() self.update() def update_after_crossover_creation(self, crossoverPairs): crossoverPairs_id = self._create_crossoverPairs_id(crossoverPairs) for d in (self.final_crossover_pairs_dict, self._final_avg_center_pairs_for_crossovers_dict): if d.has_key(crossoverPairs_id): for atm in d[crossoverPairs_id]: if self._final_crossover_atoms_dict.has_key(id(atm)): del self._final_crossover_atoms_dict[id(atm)] del d[crossoverPairs_id] def clearDictionaries(self): self._allDnaSegmentDict = {} self._base_orientation_indicator_dict = {} self._DEBUG_plane_normals_ends_for_drawing = [] self._DEBUG_avg_center_pairs_of_potential_crossovers = [] self.final_crossover_pairs_dict = {} self._final_avg_center_pairs_for_crossovers_dict = {} self._raw_crossover_atoms_dict = {} self.handleDict = {} #This dict contains all ids of all the potential cross over atoms, whose #also have their neighbor atoms in the self._raw_crossover_atoms_dict self._raw_crossover_atoms_with_neighbors_dict = {} self._final_crossover_atoms_dict = {} def getAllDnaStrandChunks(self): allDnaStrandChunkList = [] def func(node): if node.isStrandChunk(): return True return False allDnaStrandChunkList = filter(lambda m: func(m), self.win.assy.molecules) return allDnaStrandChunkList def getAllDnaSegments(self): allDnaSegmentList = [] def func(node): if isinstance(node, self.win.assy.DnaSegment): allDnaSegmentList.append(node) self.win.assy.part.topnode.apply2all(func) return allDnaSegmentList def getAllDnaSegmentsDict(self): """ """ return self._allDnaSegmentDict def _updateAllDnaSegmentDict(self): self._allDnaSegmentDict.clear() #If this preferece value is True, the search algotithm will search for #the potential crossover sites only *between* the segments in the #segment list widget (thus ignoring other segments not in that list) if env.prefs[makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key]: allDnaSegments = self.command.getSegmentList() else: allDnaSegments = self.getAllDnaSegments() for segment in allDnaSegments: if not self._allDnaSegmentDict.has_key(segment): self._allDnaSegmentDict[id(segment)] = segment def _updateCrossoverSites(self): allSegments = self._allDnaSegmentDict.values() #dict segments_searched_for_neighbors is a dictionary object that #maintains all the dna segments that have been gone trorugh a #'neighbor search' . This is used for speedups. segments_searched_for_neighbors = {} segments_to_be_searched = self.command.getSegmentList() for dnaSegment in segments_to_be_searched: self._mark_crossoverSites_bet_segment_and_its_neighbors( dnaSegment, segments_searched_for_neighbors, allSegments ) def _mark_crossoverSites_bet_segment_and_its_neighbors(self, dnaSegment, segments_searched_for_neighbors, allSegments): """ Identify the crossover sites (crossover atom pairs) between the given dnaSegment and all its neighbors (which are also DnaSegments) that fall within the specified 'crossover range'. @param dnaSegment: The DnaSegment which will be used to search for its neighboring segments and then the atoms of these will be scanned for potential crossover sites. @type dnaSegment: B{DnaSegment} @param segments_searched_for_neighbors: A dictinary object that maintains a dictionary of all segments being previously searched for their neighbors. See a comment below that explains its use. @type segments_searched_for_neighbors: dict """ #First mark the current dna segment in the dictionary #segments_searched_for_neighbors for the following purpose: #Suppose there are 4 dna segments A, B , C and D in #'allDnasegment' list. #Let the current dnaSegment be 'A'. We add it to dict #'segments_searched_for_neighbors'. #Now we search for its neighbor segments. Now we proceed in the 'for #loop' and now the current dnaSegment, whose neighbors need to be #searched is segment 'B'. Suppose segment 'B' has 'A' and 'C' as #its neighbors. But we have already searched 'A' to find its #neighbors and it should have found out 'B' as its neighbor. #So we will skip this instance in the 'sub-for-loop' that loops #through allSegmentList to find neighbors of 'B', thereby acheiving #speedup. (the 'sub-for loops is: 'for neighbor in allSegments'...) segments_searched_for_neighbors[id(dnaSegment)] = dnaSegment end1, end2 = dnaSegment.getAxisEndPoints() axisVector = norm(end2 - end1) #search through allSegments (list) to find neighbors of 'dnaSegment' #Also, skip the 'neighbor' that has already been searched for 'its' #neighbors in the toplevel 'for loop' (see explanation in the #comment above) #strandChunksOfdnaSegment is computed only once,while searching the #eligible neighbor list. 'strandChunksOfdnaSegment' gives a list #of all content strand chunks of the 'dnaSegment' currently being #searched for the eligible neighbors. strandChunksOfdnaSegment = [] for neighbor in allSegments: if not neighbor is dnaSegment and \ not segments_searched_for_neighbors.has_key(id(neighbor)): ok_to_search, orthogonal_vector = \ self._neighborSegment_ok_for_crossover_search(neighbor, end1, axisVector) if ok_to_search: #Optimization: strandChunksOfdnaSegment for the #current 'dnaSegment' is computed only once ,while #searching through its eligible neighbors. The #initial value for this list is set to [] before #the sub-for loop that iterates over the allSegments #to find neighborof 'dnaSegment' if not strandChunksOfdnaSegment: strandChunksOfdnaSegment = dnaSegment.get_content_strand_chunks() _raw_crossover_atoms_1 = self._find_raw_crossover_atoms(strandChunksOfdnaSegment, orthogonal_vector) _raw_crossover_atoms_2 = self._find_raw_crossover_atoms(neighbor.get_content_strand_chunks(), orthogonal_vector) self._find_crossover_atompairs_between_atom_dicts( _raw_crossover_atoms_1, _raw_crossover_atoms_2, orthogonal_vector) def _neighborSegment_ok_for_crossover_search( self, neighborSegment, reference_segment_end1, reference_segment_axisVector): ok_for_search = False orthogonal_vector = None neighbor_end1 , neighbor_end2 = neighborSegment.getAxisEndPoints() #Use end1 of neighbor segment and find out the perpendicular #distance (and the vector) between this atom and the #axis vector of dnaSegment (whose neighbors are being #searched). If this distance is less than a specified amount #then 'neighbor' is an approved neighbor of 'dnaSegment' if neighbor_end1 is not None: p1 = reference_segment_end1 v1 = reference_segment_axisVector p2 = neighbor_end1 dist, orthogonal_dist = orthodist(p1, v1, p2) #Check if the orthogonal distance is withing the #specified limit. if orthogonal_dist <= MAX_PERPENDICULAR_DISTANCE_BET_SEGMENT_AXES: ok_for_search = True vec = p1 + dist*v1 - p2 orthogonal_vector = orthogonal_dist*norm(vec) if self.graphicsMode.DEBUG_DRAW_PLANE_NORMALS: self._DEBUG_plane_normals_ends_for_drawing.append( (p2, (p2 + orthogonal_vector)) ) return ok_for_search, orthogonal_vector def _find_raw_crossover_atoms(self, chunkList, orthogonal_vector): available_raw_crossover_atoms_dict = {} for chunk in chunkList: indicator_atoms_dict = \ get_all_available_dna_base_orientation_indicators( chunk, orthogonal_vector, reference_indicator_dict = self._raw_crossover_atoms_dict, skip_isStrandChunk_check = True) available_raw_crossover_atoms_dict.update(indicator_atoms_dict) return available_raw_crossover_atoms_dict def _find_crossover_atompairs_between_atom_dicts(self, atom_dict_1, atom_dict_2, orthogonal_vector ): """ @see: self._filter_neighbor_atompairs() """ crossoverPairs = () #First filter dictionaries so as to include only those atoms whose #neighbor atoms are also present in that atom_dict new_atom_dict_1, atomPairsList_1 = self._filter_neighbor_atompairs( atom_dict_1) new_atom_dict_2, atomPairsList_2 = self._filter_neighbor_atompairs( atom_dict_2) if self.graphicsMode.DEBUG_DRAW_ALL_POTENTIAL_CROSSOVER_SITES: self._base_orientation_indicator_dict.update(new_atom_dict_1) self._base_orientation_indicator_dict.update(new_atom_dict_2) for atompair in atomPairsList_1: crossoverPairs = self._filter_crossover_atompairs(atompair, atomPairsList_2, orthogonal_vector) def _filter_neighbor_atompairs(self, atom_dict): """ @see: self._find_crossover_atompairs_between_atom_dicts() """ new_atom_dict = {} atomPairsList = [] for atm in atom_dict.values(): for neighbor in atm.neighbors(): if atom_dict.has_key(id(neighbor)): if self._final_crossover_atoms_dict.has_key(id(atm)) and \ self._final_crossover_atoms_dict.has_key(id(neighbor)): continue #skip this iteration if self.graphicsMode.DEBUG_DRAW_ALL_POTENTIAL_CROSSOVER_SITES: if not new_atom_dict.has_key(id(neighbor)): new_atom_dict[id(neighbor)] = neighbor if not new_atom_dict.has_key(id(atm)): new_atom_dict[id(atm)] = atm #@@BUG: What if both neighbors of atm are in atom_dict_1?? #In that case, this code creates two separate tuples with #'atm' as a common atom in each. #MAKE SURE TO append atoms in the same order as #their bond_direction. Example, if the bond is atm --> neighbor #append them as (atm, neighbor) . If bond is from #neighbor > atm, append them as (neighbor, atm). #Possible BUG: This method DOES NOT handle case with #bond_direction = 0 (simply assumes a random order) if bond_direction(atm, neighbor) == - 1: atomPairsList.append((neighbor, atm)) else: atomPairsList.append((atm, neighbor)) return new_atom_dict, atomPairsList def _filter_crossover_atompairs(self, atomPair, otherAtomPairList, orthogonal_vector): """ TODO: REVISE THIS """ for other_pair in otherAtomPairList: mate_found, distance, pairs = self._are_crossover_atompairs(atomPair, other_pair, orthogonal_vector) return None def _are_crossover_atompairs(self, atomPair1, atomPair2, orthogonal_vector): """ """ atm1, neighbor1 = atomPair1 center_1 = (atm1.posn() + neighbor1.posn())/2.0 atm2, neighbor2 = atomPair2 center_2 = (atm2.posn() + neighbor2.posn())/2.0 distance = vlen(center_1 - center_2) if distance > MAX_DISTANCE_BETWEEN_CROSSOVER_SITES: return False, distance, () #@NOTE: In self._filter_neighbor_atompairs() where we create the #atompairlists, we make sure that the atoms are ordered in +ve bond_direction #Below, we just check the relative direction of atoms. #@@@@@METHOD TO BE WRITTEN FURTHER centerVec = center_1 - center_2 if self.graphicsMode.DEBUG_DRAW_AVERAGE_CENTER_PAIRS_OF_POTENTIAL_CROSSOVERS: self._DEBUG_avg_center_pairs_of_potential_crossovers.append((center_1, center_2)) theta = angleBetween(orthogonal_vector, centerVec) if dot(centerVec, orthogonal_vector) < 1: theta = 180.0 - theta if abs(theta) > MAX_ANGLE_BET_PLANE_NORMAL_AND_AVG_CENTER_VECTOR_OF_CROSSOVER_PAIRS: return False, distance, () crossoverPairs = (atm1, neighbor1, atm2, neighbor2) for a in crossoverPairs: if not self._final_crossover_atoms_dict.has_key(id(a)): self._final_crossover_atoms_dict[id(a)] = a #important to sort this to create a unique id. Makes sure that same #crossover pairs are not added to the self.final_crossover_pairs_dict crossoverPairs_id = self._create_crossoverPairs_id(crossoverPairs) if not self.final_crossover_pairs_dict.has_key(crossoverPairs_id): self._final_avg_center_pairs_for_crossovers_dict[crossoverPairs_id] = (center_1, center_2) self.final_crossover_pairs_dict[crossoverPairs_id] = crossoverPairs return True, distance, crossoverPairs def _create_crossoverPairs_id(self, crossoverPairs): #important to sort this to create a unique id. Makes sure that same #crossover pairs are not added to the self.final_crossover_pairs_dict crossoverPairs_list = list(crossoverPairs) crossoverPairs_list.sort() crossoverPairs_id = tuple(crossoverPairs_list) return crossoverPairs_id def _createExprsHandles(self): self.handleDict = {} for crossoverPair_id in self._final_avg_center_pairs_for_crossovers_dict.keys(): handle = self._expr_instance_for_vector( self._final_avg_center_pairs_for_crossovers_dict[crossoverPair_id], self.final_crossover_pairs_dict[crossoverPair_id]) if not self.handleDict.has_key(id(handle)): self.handleDict[id(handle)] = handle def removeHandle(self, handle): if self.handleDict.has_key(id(handle)): del self.handleDict[id(handle)] self.glpane.set_selobj(None) self.glpane.gl_update() def _expr_instance_for_vector(self, pointPair, crossoverPairs): ih = get_glpane_InstanceHolder(self.glpane) expr = self._expr_for_vector(pointPair, crossoverPairs) expr_instance = ih.Instance( expr, skip_expr_compare = True) return expr_instance def _expr_for_vector(self, pointPair, crossoverPairs): handle = MakeCrossovers_Handle(pointPair[0], pointPair[1], self.glpane.scale, crossoverSite_marker = self, command = self.command, crossoverPairs = crossoverPairs ) return handle def _expr_for_vector_ORIG(self, pointPair): # WARNING: this is not optimized -- it recomputes and discards this expr on every access! # (But it looks like its caller, _expr_instance_for_imagename, caches the expr instances, # so only the uninstantiated expr itself is recomputed each time, so it's probably ok. # [bruce 080323 comment]) arrow = Highlightable(Arrow( color = black, arrowBasePoint = pointPair[0], tailPoint = pointPair[1], tailRadius = 0.8, scale = self.glpane.scale), Arrow( color = banana, arrowBasePoint = pointPair[0], tailPoint = pointPair[1], tailRadius = 0.8, scale = self.glpane.scale) ) return arrow def get_plane_normals_ends_for_drawing(self): return self._DEBUG_plane_normals_ends_for_drawing def get_avg_center_pairs_of_potential_crossovers(self): return self._DEBUG_avg_center_pairs_of_potential_crossovers def get_base_orientation_indicator_dict(self): return self._base_orientation_indicator_dict def get_final_crossover_atoms_dict(self): return self._final_crossover_atoms_dict def get_final_crossover_pairs(self): return self.final_crossover_pairs_dict.values()
NanoCAD-master
cad/src/dna/commands/MakeCrossovers/CrossoverSite_Marker.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-05-21 - 2008-06-01 Created and further refactored and modified @See: ListWidgetItems_Command_Mixin, ListWidgetItems_GraphicsMode_Mixin ListWidgetItems_PM_Mixin, CrossoverSite_Marker MakeCrossovers_GraphicsMode TODO 2008-06-01 : - See class CrossoverSite_Marker for details - more Documentation """ from exprs.If_expr import If_expr from exprs.instance_helpers import DelegatingInstanceOrExpr from exprs.Arrow import Arrow from exprs.ExprsConstants import ORIGIN from exprs.Highlightable import Highlightable from exprs.attr_decl_macros import Instance, Option, Arg from exprs.ExprsConstants import Point from utilities.constants import black, banana, copper, silver from exprs.Set import Action from exprs.__Symbols__ import _self from exprs.attr_decl_macros import State from exprs.__Symbols__ import Anything from exprs.dna_ribbon_view import Cylinder from exprs.ExprsConstants import Vector from exprs.Overlay import Overlay from exprs.Exprs import call_Expr class MakeCrossovers_Handle(DelegatingInstanceOrExpr): should_draw = State(bool, True) radius = 0.8 point1 = Arg(Point) point2 = Arg(Point) scale = Arg(float) crossoverSite_marker = Option( Action, doc = 'The CrossoverSite Marker class which instantiates this handle') #Command object specified as an 'Option' during instantiation of the class #see DnaSegment_EditCommand class definition. command = Option(Action, doc = 'The Command which instantiates this handle') crossoverPairs = Option(tuple, ()) #Stateusbar text. Variable needs to be renamed in superclass. sbar_text = Option(str, "Click on the handle to create this crossover", doc = "Statusbar text on mouseover") delegate = If_expr(_self.should_draw, Highlightable( Overlay ( Cylinder((call_Expr(_self.crossoverPairs[0].posn), call_Expr(_self.crossoverPairs[3].posn)), radius = radius, color = silver), Cylinder((call_Expr(_self.crossoverPairs[1].posn), call_Expr(_self.crossoverPairs[2].posn)), radius = radius, color = silver)), Overlay ( Cylinder((call_Expr(_self.crossoverPairs[0].posn), call_Expr(_self.crossoverPairs[3].posn)), radius = radius, color = banana), Cylinder((call_Expr(_self.crossoverPairs[1].posn), call_Expr(_self.crossoverPairs[2].posn)), radius = radius, color = banana)), on_press = _self.on_press, on_release = _self.on_release, sbar_text = sbar_text )) ##delegate = If_expr(_self.should_draw, ##Highlightable(Cylinder((point1, point2), ##radius = radius, ##color = silver), ##Cylinder((point1, point2), ##radius = radius, ##color = banana), ##on_press = _self.on_press, ##on_release = _self.on_release)) ##delegate = \ ##If_expr( ##_self.should_draw, ##Highlightable(Arrow( ##color = silver, ##arrowBasePoint = point1, ####tailPoint = norm(vector)*1.0, ##tailPoint = point2, ##radius = radius, ##scale = scale), ##Arrow( ##color = banana, ##arrowBasePoint = point1, ####tailPoint = norm(vector)*1.0, ##tailPoint = point2, ##radius = radius, ##scale = scale), ##on_press = _self.on_press, ##on_release = _self.on_release ) ) # def hasValidParamsForDrawing(self): """ Overridden in subclasses. Default implementation returns True if this object (the highlightable) can be drawn without any known issues @see: DnaStrand_ResizeHandle.hasValidParamsForDrawing for more notes. """ ##self.should_draw = True return self.should_draw def on_press(self): pass def on_release(self): self.command.makeCrossover(self.crossoverPairs) self.crossoverSite_marker.removeHandle(self)
NanoCAD-master
cad/src/dna/commands/MakeCrossovers/MakeCrossovers_Handle.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: 2008-05-21 - 2008-06-01 Created and further refactored and modified @See: ListWidgetItems_Command_Mixin, ListWidgetItems_GraphicsMode_Mixin ListWidgetItems_PM_Mixin, CrossoverSite_Marker, MakeCrossovers_Command TODO 2008-06-01 : See class CrossoverSite_Marker for details """ import foundation.env as env from PyQt4.Qt import Qt from utilities.constants import banana, silver, darkred, darkgreen, yellow from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.CS_draw_primitives import drawsphere from graphics.drawing.CS_draw_primitives import drawline from dna.commands.BuildDna.BuildDna_GraphicsMode import BuildDna_GraphicsMode from dna.commands.MakeCrossovers.ListWidgetItems_GraphicsMode_Mixin import ListWidgetItems_GraphicsMode_Mixin from dna.commands.MakeCrossovers.CrossoverSite_Marker import CrossoverSite_Marker from utilities.prefs_constants import makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key SPHERE_DRAWLEVEL = 2 SPHERE_OPACITY = 0.5 CYL_RADIUS = 1.0 CYL_OPACITY = 0.4 SPHERE_RADIUS = 2.0 SPHERE_RADIUS_FOR_TAGS = 4.0 _superclass = BuildDna_GraphicsMode class MakeCrossovers_Graphicsmode(BuildDna_GraphicsMode, ListWidgetItems_GraphicsMode_Mixin): DEBUG_DRAW_PLANE_NORMALS = False DEBUG_DRAW_AVERAGE_CENTER_PAIRS_OF_POTENTIAL_CROSSOVERS = False DEBUG_DRAW_ALL_POTENTIAL_CROSSOVER_SITES = False _crossoverSite_marker = None _handleDrawingRequested = True #@see: self.leftADown where this flag is set. # It is then used in self.leftADrag. _should_update_crossoverSites_during_leftDrag = False #Used to log a message in the command.propMgr.See self.leftDrag, self.leftUp #This flag ensures that its done only once during left drag. Needs cleanup. #this attr was introduced just before v1.1.0 release--Ninad 2008-06-03 _leftDrag_logMessage_emitted = False def __init__(self, glpane): _superclass.__init__(self, glpane) self._handleDrawingRequested = True self._createCrossoverSite_Marker_if_needed() def _createCrossoverSite_Marker_if_needed(self): if self._crossoverSite_marker is None: self._crossoverSite_marker = CrossoverSite_Marker(self) def Enter_GraphicsMode(self): _superclass.Enter_GraphicsMode(self) self._createCrossoverSite_Marker_if_needed() self._crossoverSite_marker.update() def clearDictionaries(self): self._crossoverSite_marker.clearDictionaries() def get_final_crossover_pairs(self): return self._crossoverSite_marker.get_final_crossover_pairs() def updateExprsHandleDict(self): self._crossoverSite_marker.updateExprsHandleDict() def update_after_crossover_creation(self, crossoverPairs): self._crossoverSite_marker.update_after_crossover_creation(crossoverPairs) def updateCrossoverSites(self): """ Delegates the responsibility of updating all crossover sites in the 3D wokspace to the self._crossoverSite_marker. """ self._crossoverSite_marker.update() def update_cursor_for_no_MB(self): """ Update the cursor for no mouse button pressed """ _superclass.update_cursor_for_no_MB(self) ListWidgetItems_GraphicsMode_Mixin.update_cursor_for_no_MB(self) def keyPressEvent(self, event): """ Handles keyPressEvent. Overrides superclass method. If delete key is pressed while the focus is inside the PM list widget, it deletes that list widget item. @see: ListWidgetItems_PM_Mixing.listWidgetHasFocus() @TODO: Calls self.command.propMgr object which is better to avoid... """ if event.key() == Qt.Key_Delete: if self.command.propMgr and self.command.propMgr.listWidgetHasFocus(): self.command.propMgr.removeListWidgetItems() return _superclass.keyPressEvent(self, event) def leftADown(self, objectUnderMouse, event): """ Overrides superclass method. This method also sets flag used in self.leftDrag that decide whether to compute the crossover sites during the left drag.Example: If user is dragging a dnaSegment that is is not included in the crossover site search, it skips the computation during the left drag. Thus providing a minor optimization. """ _superclass.leftADown(self, objectUnderMouse, event) if not env.prefs[makeCrossoversCommand_crossoverSearch_bet_given_segments_only_prefs_key]: self._should_update_crossoverSites_during_leftDrag = True elif self._movable_dnaSegment_for_leftDrag and \ self._movable_dnaSegment_for_leftDrag in self.command.getSegmentList(): self._should_update_crossoverSites_during_leftDrag = True else: self._should_update_crossoverSites_during_leftDrag = False def chunkLeftUp(self, a_chunk, event): """ Overrides superclass method. If add or remove segmets tool is active, upon leftUp , when this method gets called, it modifies the list of segments being resized by self.command. @see: self.update_cursor_for_no_MB() @see: self.end_selection_from_GLPane() """ ListWidgetItems_GraphicsMode_Mixin.chunkLeftUp(self, a_chunk, event) _superclass.chunkLeftUp(self, a_chunk, event) def leftUp(self, event): _superclass.leftUp(self, event) self._crossoverSite_marker.updateHandles() if self._leftDrag_logMessage_emitted: self.command.logMessage('LEFT_DRAG_FINISED') if not self._handleDrawingRequested: self._handleDrawingRequested = True self._leftDrag_logMessage_emitted = False def editObjectOnSingleClick(self): """ Overrides superclass method. If this method returns True, when you left click on a DnaSegment or a DnaStrand, it becomes editable (i.e. program enters the edit command of that particular object if that object is editable). If this returns False, program simply stays in the current command. @see: BuildDna_GraphicsMode.editObjectOnSingleClick() """ return False def leftDrag(self, event): """ Overrides superclass method. Also updates the potential crossover sites. """ _superclass.leftDrag(self, event) self._handleDrawingRequested = False if self._should_update_crossoverSites_during_leftDrag: self._crossoverSite_marker.partialUpdate() if not self._leftDrag_logMessage_emitted: self._leftDrag_logMessage_emitted = True self.command.logMessage('LEFT_DRAG_STARTED') def end_selection_from_GLPane(self): """ Overrides superclass method. In addition to selecting or deselecting the chunk, if a tool that adds Dna segments to the segment list in the property manager is active, this method also adds the selected dna segments to that list. Example, if user selects 'Add Dna segments' tool and does a lasso selection , then this also method adds the selected segments to the list. Opposite behavior if the 'remove segments from segment list too, is active) """ _superclass.end_selection_from_GLPane(self) ListWidgetItems_GraphicsMode_Mixin.end_selection_from_GLPane(self) def Draw_other(self): _superclass.Draw_other(self) if self._handleDrawingRequested: self._drawHandles() def _drawHandles(self): if self._crossoverSite_marker and self._crossoverSite_marker.handleDict: for handle in self._crossoverSite_marker.handleDict.values(): if handle is not None: #if handle is None its a bug! handle.draw() def _drawSpecialIndicators(self): final_crossover_atoms_dict = self._crossoverSite_marker.get_final_crossover_atoms_dict() for atm in final_crossover_atoms_dict.values(): sphere_radius = max(1.20*atm.drawing_radius(), SPHERE_RADIUS) drawsphere(darkgreen, atm.posn(), sphere_radius, SPHERE_DRAWLEVEL, opacity = SPHERE_OPACITY) if self.DEBUG_DRAW_ALL_POTENTIAL_CROSSOVER_SITES: atom_dict = self._crossoverSite_marker.get_base_orientation_indicator_dict() for atm in atom_dict.values(): drawsphere(darkred, atm.posn(), 1.5, SPHERE_DRAWLEVEL, opacity = SPHERE_OPACITY) if self.DEBUG_DRAW_PLANE_NORMALS: self._DEBUG_drawPlaneNormals() if self.DEBUG_DRAW_AVERAGE_CENTER_PAIRS_OF_POTENTIAL_CROSSOVERS: self._DEBUG_draw_avg_centerpairs_of_potential_crossovers() def _drawTags(self): """ Overrides _superClass._drawTags() for self._tagPositions. @see: self.drawTag() @see: GraphicsMode._drawTags() @see: class PM_SelectionWidget """ if self._tagPositions: for point in self._tagPositions: drawsphere(banana, point, SPHERE_RADIUS_FOR_TAGS , SPHERE_DRAWLEVEL, opacity = SPHERE_OPACITY) def _DEBUG_drawPlaneNormals(self): ends = self._crossoverSite_marker.get_plane_normals_ends_for_drawing() for end1, end2 in ends: drawcylinder(banana, end1, end2, CYL_RADIUS, capped = True, opacity = CYL_OPACITY ) def _DEBUG_draw_avg_centerpairs_of_potential_crossovers(self): pairs = self._crossoverSite_marker.get_avg_center_pairs_of_potential_crossovers for pair in pairs: drawline(yellow, pair[0], pair[1], width = 2)
NanoCAD-master
cad/src/dna/commands/MakeCrossovers/MakeCrossovers_GraphicsMode.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: TODO: See ListWidgetItems_Command_Mixin for details. @see: MakeCrossovers_PropertyManager ListWidgetItems_Command_Mixin ListWidgetItems_GraphicsMode_Mixin """ from PM.PM_SelectionListWidget import PM_SelectionListWidget from utilities.constants import lightred_1, lightgreen_2 from PyQt4.Qt import Qt from PM.PM_ToolButton import PM_ToolButton from PM.PM_WidgetRow import PM_WidgetRow class ListWidgetItems_PM_Mixin: def _loadSegmentListWidget(self, pmGroupBox): self.segmentListWidget = PM_SelectionListWidget( pmGroupBox, self.win, label = "", heightByRows = 12) self.segmentListWidget.setFocusPolicy(Qt.StrongFocus) self.segmentListWidget.setFocus() self.setFocusPolicy(Qt.StrongFocus) self.addSegmentsToolButton = PM_ToolButton( pmGroupBox, text = "Add segments to the list", iconPath = "ui/actions/Properties Manager"\ "/AddSegment_To_ResizeSegmentList.png", spanWidth = True ) self.addSegmentsToolButton.setCheckable(True) self.addSegmentsToolButton.setAutoRaise(True) self.removeSegmentsToolButton = PM_ToolButton( pmGroupBox, text = "Remove segments from the list", iconPath = "ui/actions/Properties Manager"\ "/RemoveSegment_From_ResizeSegmentList.png", spanWidth = True ) self.removeSegmentsToolButton.setCheckable(True) self.removeSegmentsToolButton.setAutoRaise(True) #Widgets to include in the widget row. widgetList = [ ('QLabel', " Add/Remove Segments:", 0), ('QSpacerItem', 5, 5, 1), ('PM_ToolButton', self.addSegmentsToolButton, 2), ('QSpacerItem', 5, 5, 3), ('PM_ToolButton', self.removeSegmentsToolButton, 4), ('QSpacerItem', 5, 5, 5) ] widgetRow = PM_WidgetRow(pmGroupBox, title = '', widgetList = widgetList, label = "", spanWidth = True ) def listWidgetHasFocus(self): """ Checks if the list widget that lists dnasegments (that will undergo special operations such as 'resizing them at once or making crossovers between the segments etc) has the Qt focus. This is used to just remove items from the list widget (without actually 'deleting' the corresponding Dnasegment in the GLPane) @see: MultipleDnaSegment_GraphicsMode.keyPressEvent() where it is called """ if self.segmentListWidget.hasFocus(): return True return False def updateListWidgets(self): self.updateSegmentListWidget() def updateSegmentListWidget(self): """ Update the list of segments shown in the segments list widget @see: self.updateListWidgets, self.updateStrandListWidget """ segmentList = [] segmentList = self.command.getSegmentList() if segmentList: self.segmentListWidget.insertItems( row = 0, items = segmentList) else: self.segmentListWidget.clear() def isAddSegmentsToolActive(self): """ Returns True if the add segments tool (which adds the segments to the list of segments) is active """ if self.addSegmentsToolButton.isChecked(): #For safety if not self.removeSegmentsToolButton.isChecked(): return True return False def isRemoveSegmentsToolActive(self): """ Returns True if the remove segments tool (which removes the segments from the list of segments ) is active """ if self.removeSegmentsToolButton.isChecked(): if not self.addSegmentsToolButton.isChecked(): #For safety return True return False def activateAddSegmentsTool(self,enable): """ Change the appearance of the list widget (that lists the dna segments ) so as to indicate that the add dna segments tool is active @param enable: If True, changes the appearance of list widget to indicate that the add segments tool is active. @type enable: bool """ if enable: if not self.addSegmentsToolButton.isChecked(): self.addSegmentsToolButton.setChecked(True) if self.removeSegmentsToolButton.isChecked(): self.removeSegmentsToolButton.setChecked(False) self.segmentListWidget.setAlternatingRowColors(False) self.segmentListWidget.setColor(lightgreen_2) self.command.logMessage('ADD_SEGMENTS_ACTIVATED') else: if self.addSegmentsToolButton.isChecked(): self.addSegmentsToolButton.setChecked(False) self.segmentListWidget.setAlternatingRowColors(True) self.segmentListWidget.resetColor() def activateRemoveSegmentsTool(self,enable): """ Change the appearance of the list widget (that lists the dna segments ) so as to indicate that the REMOVE dna segments tool is active @param enable: If True, changes the appearance of list widget to indicate that the REMOVE segments tool is active. @type enable: bool """ if enable: if not self.removeSegmentsToolButton.isChecked(): self.removeSegmentsToolButton.setChecked(True) if self.addSegmentsToolButton.isChecked(): self.addSegmentsToolButton.setChecked(False) self.segmentListWidget.setAlternatingRowColors(False) self.command.logMessage('REMOVE_SEGMENTS_ACTIVATED') self.segmentListWidget.setColor(lightred_1) else: if self.removeSegmentsToolButton.isChecked(): self.removeSegmentsToolButton.setChecked(False) self.segmentListWidget.setAlternatingRowColors(True) self.segmentListWidget.resetColor() def _deactivateAddRemoveSegmentsTool(self): """ Deactivate tools that allow adding or removing the segments to the segment list in the Property manager. This can be simply done by resetting the state of toolbuttons to False. Example: toolbuttons that add or remove segments to the segment list in the Property manager. When self.show is called these need to be unchecked. @see: self.isAddSegmentsToolActive() @see:self.isRemoveSegmentsToolActive() @see: self.show() """ self.addSegmentsToolButton.setChecked(False) self.removeSegmentsToolButton.setChecked(False) def removeListWidgetItems(self): """ Removes selected itoms from the dna segment list widget Example: User selects a bunch of items in the list widget and hits delete key to remove the selected items from the list IMPORTANT NOTE: This method does NOT delete the correspoinging model item in the GLPane (i.e. corresponding dnasegment). It just 'removes' the item from the list widget This is intentional. """ self.segmentListWidget.deleteSelection() itemDict = self.segmentListWidget.getItemDictonary() self.command.setSegmentList(itemDict.values()) self.updateListWidgets() self.win.win_update()
NanoCAD-master
cad/src/dna/commands/MakeCrossovers/ListWidgetItems_PM_Mixin.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: TODO: See ListWidgetItems_Command_Mixin for details. @see: MakeCrossovers_GraphicsMode ListWidgetItems_Command_Mixin ListWidgetItems_PM_Mixin """ class ListWidgetItems_GraphicsMode_Mixin: def update_cursor_for_no_MB(self): """ Update the cursor for no mouse button pressed """ if self.command: if self.command.isAddSegmentsToolActive(): self.o.setCursor(self.win.addSegmentToResizeSegmentListCursor) return if self.command.isRemoveSegmentsToolActive(): self.o.setCursor(self.win.removeSegmentFromResizeSegmentListCursor) return def chunkLeftUp(self, a_chunk, event): """ Overrides superclass method. If add or remove segments tool is active, upon leftUp, when this method gets called, it modifies the list of segments by self.command. @see: self.update_cursor_for_no_MB() @see: self.end_selection_from_GLPane() """ if self.command.isAddSegmentsToolActive() or \ self.command.isRemoveSegmentsToolActive(): if a_chunk.isAxisChunk(): segmentGroup = a_chunk.parent_node_of_class( self.win.assy.DnaSegment) if segmentGroup is not None: if self.command.isAddSegmentsToolActive(): segmentList = [segmentGroup] self.command.ensureSegmentListItemsWithinLimit(segmentList) if self.command.isRemoveSegmentsToolActive(): self.command.removeSegmentFromSegmentList(segmentGroup) self.end_selection_from_GLPane() return def end_selection_from_GLPane(self): """ Overrides superclass method. In addition to selecting or deselecting the chunk, if a tool that adds Dna segments to the segment list in the property manager is active, this method also adds the selected dna segments to that list. Example, if user selects 'Add Dna segments' tool and does a lasso selection , then this also method adds the selected segments to the list. Opposite behavior if the 'remove segments from segment list too, is active) """ selectedSegments = self.win.assy.getSelectedDnaSegments() if self.command.isAddSegmentsToolActive(): self.command.ensureSegmentListItemsWithinLimit(selectedSegments) if self.command.isRemoveSegmentsToolActive(): for segment in selectedSegments: self.command.removeSegmentFromSegmentList(segment)
NanoCAD-master
cad/src/dna/commands/MakeCrossovers/ListWidgetItems_GraphicsMode_Mixin.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ A_Dna_PAM3_Generator.py -- DNA duplex generator helper class, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env from platform_dependent.PlatformDependent import find_plugin_dir from utilities.Log import orangemsg basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) from dna.generators.A_Dna_Generator import A_Dna_Generator class A_Dna_PAM3_Generator(A_Dna_Generator): """ Provides a PAM5 reduced model of the B form of DNA. @attention: This class is not implemented yet. """ model = "PAM3"
NanoCAD-master
cad/src/dna/generators/A_Dna_PAM3_Generator.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ B_Dna_PAM3_Generator_SingleStrand allows resizing a single strand of a DNA. See self.modify(). Note that self.make() to create a DnaStrnad from scratch is not implemented as of 2008-04-02. @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: Created on 2008-04-02 TODO as of 2008-04-07 - add more documentation. may undergo major refactoring/renaming changes. - post FNANO allow resizing of a single strand such that: if axis atoms on original dna match with the ones on the newly created single stranded dna, delete those atoms and fuse the bare strand with existing atoms - May be revise the dna creation process thoughout. Example, see how to generate positions of strand-axis atoms without using the old way of inserting bases from mmp and performing transforms on them. - move this file to dna/model - Methods such as the following need REVIEW post FNANO08 (not urgent). May be revise algorithm for optimization or supporting some features such as 'extend and bond self._fuse_new_dna_with_original_duplex self._replace_overlapping_axisAtoms_of_new_dna """ from geometry.VQT import Q, norm, vlen, cross from Numeric import dot from utilities.debug import print_compact_stack from model.bonds import bond_at_singlets from dna.generators.B_Dna_PAM3_Generator import B_Dna_PAM3_Generator class B_Dna_PAM3_SingleStrand_Generator(B_Dna_PAM3_Generator): """ B_Dna_PAM3_SingleStrand_Generator allows resizing a single strand of a DNA. See self.modify(). Note that self.make() to create a DnaStrnad from scratch is not implemented as of 2008-04-02. @see: superclass B_Dna_PAM3_Generator for more documentation, """ def _strandAinfo(self, index): """ Returns parameters needed to add the next base of the @param index: Base-pair index. @type index: int """ #unused param index. Just inheriting from the superclass.. del index zoffset = 0.0 thetaOffset = 0.0 basename = "PAM3-SingleStrand/MiddleBasePair" basefile = self._baseFileName(basename) return (basefile, zoffset, thetaOffset) def _orient_for_modify(self, end1, end2): """ Do the final orientation of the newly generated dna, around its own axis so that the axis and strand atoms on this new dna are fusable with the resize end on the original dna. @param end1: end1 of new dna (segment) generated @param end2: end2 of new dna (segment) generated """ b = norm(end2 - end1) new_ladder = self.axis_atom_end1.molecule.ladder chunkListForRotation = new_ladder.all_chunks() endBaseAtomList = new_ladder.get_endBaseAtoms_containing_atom(self.axis_atom_end1) endStrandbaseAtoms = (endBaseAtomList[0], endBaseAtomList[2]) self.strandA_atom_end1 = None #TODO: REVIEW / REFACTOR THIS and DOC for atm in endStrandbaseAtoms: if atm is not None: self.strandA_atom_end1 = atm self._set_bond_direction_on_new_strand(atm) axis_strand_vector = (self.strandA_atom_end1.posn() - \ self.axis_atom_end1.posn()) vectorAlongLadderStep = self._resizeEndStrand1Atom.posn() - \ self._resizeEndAxisAtom.posn() unitVectorAlongLadderStep = norm(vectorAlongLadderStep) self.final_pos_strand_end_atom = \ self.axis_atom_end1.posn() + \ vlen(axis_strand_vector)*unitVectorAlongLadderStep q_new = Q(axis_strand_vector, vectorAlongLadderStep) if dot(axis_strand_vector, cross(vectorAlongLadderStep, b)) < 0: q_new2 = Q(b, -q_new.angle) else: q_new2 = Q(b, q_new.angle) self.assy.rotateSpecifiedMovables(q_new2, chunkListForRotation, end1) def _strand_neighbors_to_delete(self, axisAtom): """ Returns a list of strand neighbors of the given axis atom to delete from the original dna being resized (and resizing will result in removing bases/ basepairs from the dna). This method determines whether both the strand neigbors of this axisAtom need to be deleted or is it just a single strand neighbor on a specific Dna Strand Group needs to be deleted. The latter is the case while resizing a single strand of a Dna. i.e. in this class, it will find a strand neighbor to the given axis atom on the strand being resized. @see: self._remove_bases_from_dna() where this is called. @see: B_Dna_PAM3_Generator._strand_neighbors_to_delete() -- overridden here """ #Note that sicne we are resizing a single strand, the list this #method returns will have only one strand atom or will be empty if #strand atom on the strand being resized is not found. # strand_neighbors_to_delete = [] strand_neighbors = axisAtom.strand_neighbors() if self._resizeEndStrand1Atom: mol = self._resizeEndStrand1Atom.molecule resize_strand = mol.parent_node_of_class(self.assy.DnaStrand) for atm in strand_neighbors: strand = atm.molecule.parent_node_of_class(self.assy.DnaStrand) if strand is resize_strand: strand_neighbors_to_delete = [atm] break return strand_neighbors_to_delete def _set_bond_direction_on_new_strand(self, strandEndAtom_of_new_strand ): """ Set the bond direction on the new strand. The bond direction will be set such that the new strand can be fused with the strand being resized Example: if the last strand atom of strand being resized is a 5' end atom, this method will make sure that the first strand end atom of the new strand we created is a 3' end. @param strandEndAtom_of_new_strand: The strand end base atom on the new strand. The bond direction will be set from this atom and will be propogated further along the strand atom chain this atom belongs to (of the new strand) @type strandEndAtom_of_new_strand: B{Atom} """ atm = strandEndAtom_of_new_strand strand_bond = None for bnd in atm.bonds: if bnd.is_directional(): strand_bond = bnd break if strand_bond: mol = self._resizeEndStrand1Atom.molecule orig_dnaStrand = mol.parent_node_of_class(self.assy.DnaStrand) five_prime_orig, three_prime_orig = \ orig_dnaStrand.get_strand_end_base_atoms() if self._resizeEndStrand1Atom is five_prime_orig: #+1 indicates the absolute bond direction i.e. from 5' to 3' end strand_bond.set_bond_direction_from(atm, +1, propogate = True) elif self._resizeEndStrand1Atom is three_prime_orig: strand_bond.set_bond_direction_from(atm, - 1, propogate = True) def _replace_overlapping_axisAtoms_of_new_dna(self, new_endBaseAtomList): """ Checks if the new dna (which is a single strand in this class) has any axis atoms that overlap the axis atoms of the original dna. If it finds such atoms, the such overlapping atoms of the new dna are replaced with that on the original dna. Because of this operation, the strand atoms of the new dna are left without axis atoms. So, this method then calls appropriate method to create bonds between new strand atoms and corresponding axis atoms of the original dna. Also, the replacement operation could leave out some neighboring axis atoms of the *new dna* without bonds. So those need to be bonded with the axis atom of the original dna which replaced their neighbor. This is done by calling self._bond_axisNeighbors_with_orig_axisAtoms() @see self._fuse_new_dna_with_original_duplex() for a detail example @see: self._bond_bare_strandAtoms_with_orig_axisAtoms() @see self._bond_axisNeighbors_with_orig_axisAtoms() @BUG: Bug or unsupported feature: If the axis atoms of the original dna have a broken bond in between, then the wholechain will stop at the broken bond and thus, overlapping axis atoms of new dna after that bond won't be removed --- in short, the extended strand won't be properly fused. We need to come up with well defined rules ..example -- when the strand should decide it needs to remove overlapping atoms? ...even when it is overlapping with a different dna? (not the one we are resizing ) etc. """ #new dna generated by self.modify endAxisAtom_new_dna = new_endBaseAtomList[1] axis_wholechain_new_dna = endAxisAtom_new_dna.molecule.wholechain atomlist_with_overlapping_atoms = axis_wholechain_new_dna.get_all_baseatoms() #dna being resized (the original structure which is being resized) axis_wholechain_orig_dna = self._resizeEndAxisAtom.molecule.wholechain atomlist_to_keep = axis_wholechain_orig_dna.get_all_baseatoms() axisEndBaseAtoms_orig_dna = axis_wholechain_orig_dna.end_baseatoms() overlapping_atoms = \ self._find_overlapping_axisAtomPairs(atomlist_to_keep, atomlist_with_overlapping_atoms) axis_and_strand_atomPairs_to_bond = [] axis_and_axis_atomPairs_to_bond = [] fusableAxisAtomPairsDict = {} for atm_to_keep, atm_to_delete in overlapping_atoms: #Make sure that atm_to_keep (the axis atom on original dna) #has only one strand neighbor, OTHERWISE , if we delete #the overlapping axis atoms on the new dna, the bare strand of #the new dna can not be bonded with the old dna axis! and we #will endup having a bare strand with no axis atom! #-Ninad 2008-04-04 strand_neighbors_of_atm_to_keep = atm_to_keep.strand_neighbors() #Before deleting the overlapping axis atom of the new dna, #make sure that the corresponding old axis atom has only #one strand neighbor. Otherwise, there will be no axis atom #available for the bare strand atom that will result because #of this delete operation! if len(strand_neighbors_of_atm_to_keep) == 1 and atm_to_delete: #We know that the new dna is a single strand. So the #axis atom will ONLY have a single strand atom atatched. #If not, it will be a bug! strand_atom_new_dna = atm_to_delete.strand_neighbors()[0] #We will fuse this strand atom to the old axis atom axis_and_strand_atomPairs_to_bond.append((atm_to_keep, strand_atom_new_dna)) fusableAxisAtomPairsDict[atm_to_keep] = atm_to_delete ##fusableAxisAtomPairs.append((atm_to_keep, atm_to_delete)) for atm_to_keep in axisEndBaseAtoms_orig_dna: #This means that we are at the end of the chain of the #original dna. There could be some more axis atoms on the #new dna that go beyond the original dna axis chain -- [A] #Thus, after we replace the overlapping axis atoms of the #new dna with the original axis atoms, we should make sure #to bond them with the atoms [A] mentioned above if fusableAxisAtomPairsDict.has_key(atm_to_keep): atm_to_delete = fusableAxisAtomPairsDict[atm_to_keep] for neighbor in atm_to_delete.axis_neighbors(): if neighbor is not None and \ neighbor not in fusableAxisAtomPairsDict.values(): axis_and_axis_atomPairs_to_bond.append((atm_to_keep, neighbor)) for atm_to_delete in fusableAxisAtomPairsDict.values(): try: #Now delete the overlapping axis atom on new dna atm_to_delete.kill() except: print_compact_stack("Strand resizing: Error killing axis atom") if axis_and_strand_atomPairs_to_bond: self._bond_bare_strandAtoms_with_orig_axisAtoms(axis_and_strand_atomPairs_to_bond) if axis_and_axis_atomPairs_to_bond: self._bond_axisNeighbors_with_orig_axisAtoms(axis_and_axis_atomPairs_to_bond) def _bond_bare_strandAtoms_with_orig_axisAtoms(self, axis_and_strand_atomPairs_to_bond): """ Create bonds between the bare strand atoms of the new dna with the corresponding axis atoms of the original dna. This method should be called ONLY from self._replace_overlapping_axisAtoms_of_new_dna() where we remove the axis atoms of new dna that overlap the ones in old dna. We need to re-bond the bare strand atoms as a result of this replacment, with the axis atoms of the old dna. @param axis_and_strand_atomPairs_to_bond: A list containing pairs of the axis and strand atoms that will be bonded together. It is of the format [(atm1, atm2) , ....] Where, atm1 is always axisAtom of original dna atm2 is always bare strandAtom of new dna @type axis_and_strand_atomPairs_to_bond: list @see: self._replace_overlapping_axisAtoms_of_new_dna() which calls this. """ #@REVIEW/ TODO: Make sure that we are not bondingan axis atom with a #5' or 3' bondpoint of the strand atom.Skip the pair if its one and #the same atom (?) This may not be needed because of the other #code but is not obvious , so better to make sure in this method #-- Ninad 2008-04-11 for atm1, atm2 in axis_and_strand_atomPairs_to_bond: #Skip the pair if its one and the same atom. if atm1 is not atm2: for s1 in atm1.singNeighbors(): if atm2.singNeighbors(): s2 = atm2.singNeighbors()[0] bond_at_singlets(s1, s2, move = False) #REVIEW 2008-04-10 if 'break' is needed - break #Alternative-- Use find bondable pairs using class fuseChunksBase # Fuse the base-pair chunks together into continuous strands. #But this DOESN't WORK if bondpoints are disoriented or beyond the #tolerance limit. So its always better to bond atoms explicitely as done #above ##from commands.Fuse.fusechunksMode import fusechunksBase ##fcb = fusechunksBase() ##fcb.tol = 2.0 ##fcb.find_bondable_pairs_in_given_atompairs(axis_and_strand_atomPairs_to_bond) ##fcb.make_bonds(self.assy) def _bond_axisNeighbors_with_orig_axisAtoms(self, axis_and_axis_atomPairs_to_bond ): """ The operation that replaces the overlapping axis atoms of the new dnas with the corresponding axis atoms of the original dna could leave out some neighboring axis atoms of the *new dna* without bonds. So those need to be bonded with the axis atom of the original dna which replaced their neighbor. This method does that job. @param axis_and_axis_atomPairs_to_bond: A list containing pairs of the axis atom of original dna and axis atom on the new dna (which was a neighbor of the atom deleted in the replacement operation and was bonded to it) . Thies eatoms will be bonded with each other. It is of the format [(atm1, atm2) , ....] Where, atm1 is always axisAtom of original dna which replaced the overlapping axis atom of new dna (and thereby broke bond between that atom's axis neighbors ) atm2 is always axis Atom of new dna , that was a neighbor to an axis atom, say 'A', replaced by original dna axis atom (because 'A' was overlapping) and was previously bonded to 'A'. """ for atm1, atm2 in axis_and_axis_atomPairs_to_bond: #Skip the pair if its one and the same atom. if atm1 is atm2: continue #the following check (atm1.singNeighbors()) < 1....)doesn't work in #some cases! So explicitly checking the length of the bondpoint #neighbors of the atom in the for loop afterwords. ##if len(atm1.singNeighbors()) < 1 or len(atm2.singNeighbors()) < 1: ##continue #Loop through bondpoints of atm1 for s1 in atm1.singNeighbors(): #bond point neigbors of atm2 if atm2.singNeighbors(): s2 = atm2.singNeighbors()[0] bond_at_singlets(s1, s2, move = False) break def _fuse_new_dna_with_original_duplex(self, new_endBaseAtomList, endBaseAtomList): """ First it fuses the end axis and strand atoms of the new dna with the corresponding end base atoms of the original dna. Then, it checks if the new dna (which is a single strand in this class) has any axis atoms that overlap the axis atoms of the original dna. If it finds such atoms, the such overlapping atoms of the new dna are replaced with that on the original dna. (This is done by calling self._replace_overlapping_axisAtoms_of_new_dna()) EXAMPLE: Figure A: Figure A shows the original dna -- * denote the axis atoms and we will be resizing strand (2) (1) 3' <--<--<--<--<--<--<--<--<--<--<--<--< 5' | | | | | | | | | | | | | (A) *--*--*--*--*--*--*--*--*--*--*--*--* | | | | | | | | | | | | | (2) 5' >-->-->-->-->-->3' Figure B: Lets assume that we extend strand (2) by 4 bases. So, the new dna that we will create in self.modify() is indicated by the strand (2) with symbols 'X' for strand base atoms and symbol 'o' for the axis base atoms. Clearly, the axis atoms 'o' overlap the axis atoms of the original dna. So we will remove those. As a result of this replacement, strand atoms 'X' will be without any axis atoms , so we will bond them with the original axis atoms '*'. The overall result is the original duplex's strand 2 gets extended by 4 bases and it still remains connected with the corresponding bases in strand (1) (the complementary strand ) (1) 3' <--<--<--<--<--<--<--<--<--<--<--<--< 5' | | | | | | | | | | | | | (A) *--*--*--*--*--*--o--o--o--o--*--*--* | | | | | | | | | | | | | (2) 5' >-->-->-->-->-->==X==X==X==X> @see self._replace_overlapping_axisAtoms_of_new_dna() for more details TODO: - method needs to be renamed The original dna may be a single stranded dna or a duplex. Until 2008-04-02 ,it was possible to create or modify only a duplex and thats why the name 'duplex' - Refactor further. May be use superclass method with some mods. @see: self.modify() @see: B_Dna_PAM3_Generator._fuse_new_dna_with_original_duplex() """ #FUSE new dna strand with the original duplex chunkList1 = \ [ new_endBaseAtomList[0].molecule, self._resizeEndStrand1Atom.molecule] chunkList2 = \ [ new_endBaseAtomList[1].molecule, self._resizeEndAxisAtom.molecule] #Set the chunk color and chunk display of the new duplex such that #it matches with the original duplex chunk color and display #Actually, fusing the chunks should have taken care of this, but #for some unknown reasons, its not happening. May be because #chunks are not 'merged'? ... Setting display and color for new #duplex chunk is explicitely done below. Fixes bug 2711 for chunkPair in (chunkList1, chunkList2): display = chunkPair[1].display color = chunkPair[1].color chunkPair[0].setDisplayStyle(display) if color: chunkPair[0].setcolor(color) #Original implementation which relied on on fuse chunks for finding #bondable atom pairs within a tolerance limit. This is no longer #used and can be removed after more testing of explicit bonding #done in self._bond_atoms_in_atomPairs() (called below) #-- Ninad 2008-04-11 ##self.fuseBasePairChunks(chunkPair) endAtomPairsToBond = [ (new_endBaseAtomList[0], self._resizeEndStrand1Atom), (new_endBaseAtomList[1], self._resizeEndAxisAtom)] #Create explicit bonds between the end base atoms #(like done in self._bond_bare_strandAtoms_with_orig_axisAtoms()) #instead of relying on fuse chunks (which relies on finding #bondable atom pairs within a tolerance limit. This fixes bug 2798 self._bond_atoms_in_atomPairs(endAtomPairsToBond) #Make sure to call this AFTER the endatoms of new and #original DNAs are joined. Otherwise (if you replace the overlapping #atoms first), if the endAxisAtom of the new dna is an overlapping #atom, it will get deleted and in turn it will invalidate the #new_endBaseAtomList! (and thus, even the end strand atom won't #be fused with original dna end strand atom) self._replace_overlapping_axisAtoms_of_new_dna(new_endBaseAtomList) def _find_overlapping_axisAtomPairs(self, atomlist_to_keep, atomlist_with_overlapping_atoms, tolerance = 1.1 ): """ @param atomlist_to_keep: Atomlist which will be used as a reference atom list. The atoms in this list will be used to find the atoms in the *other list* which overlap atom positions in *this list*. Thus, the atoms in 'atomlist_to_keep' will be preserved (and thus won't be appended to self.overlapping_atoms) @type atomlist_to_keep: list @param atomlist_with_overlapping_atoms: This list will be checked with the first list (atom_list_to_keep) to find overlapping atoms. The atoms in this list that overlap with the atoms from the original list will be appended to self.overlapping_atoms (and will be eventually deleted) """ overlapping_atoms_to_delete = [] # Remember: chunk = a selected chunk = atomlist to keep # mol = a non-selected -- to find overlapping atoms from # Loop through all the atoms in the selected chunk. # Use values() if the loop ever modifies chunk or mol-- for a1 in atomlist_to_keep: # Singlets can't be overlapping atoms. SKIP those if a1.is_singlet(): continue # Loop through all the atoms in atomlist_with_overlapping_atoms. for a2 in atomlist_with_overlapping_atoms: # Only atoms of the same type can be overlapping. # This also screens singlets, since a1 can't be a # singlet. if a1.element is not a2.element: continue # Compares the distance between a1 and a2. # If the distance # is <= tol, then we have an overlapping atom. # I know this isn't a proper use of tol, # but it works for now. Mark 050901 if vlen (a1.posn() - a2.posn()) <= tolerance: # Add this pair to the list-- overlapping_atoms_to_delete.append( (a1,a2) ) # No need to check other atoms in this chunk-- break return overlapping_atoms_to_delete
NanoCAD-master
cad/src/dna/generators/B_Dna_PAM3_SingleStrand_Generator.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ DnaDuplex.py -- DNA duplex generator helper classes, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env import os from math import sin, cos, pi from utilities.debug import print_compact_traceback, print_compact_stack from platform_dependent.PlatformDependent import find_plugin_dir from files.mmp.files_mmp import readmmp from geometry.VQT import Q, V, angleBetween, cross, vlen from utilities.Log import orangemsg from utilities.exception_classes import PluginBug from utilities.constants import gensym from utilities.prefs_constants import dnaDefaultStrand1Color_prefs_key from utilities.prefs_constants import dnaDefaultStrand2Color_prefs_key from utilities.prefs_constants import dnaDefaultSegmentColor_prefs_key from dna.model.Dna_Constants import getDuplexBasesPerTurn ##from dna.updater.dna_updater_prefs import pref_dna_updater_convert_to_PAM3plus5 from simulation.sim_commandruns import adjustSinglet from model.elements import PeriodicTable from model.Line import Line from model.chem import Atom_prekill_prep Element_Ae3 = PeriodicTable.getElement('Ae3') from dna.model.Dna_Constants import basesDict, dnaDict from dna.model.dna_model_constants import LADDER_END0 basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) RIGHT_HANDED = -1 LEFT_HANDED = 1 from geometry.VQT import V, Q, norm, cross from geometry.VQT import vlen from Numeric import dot from utilities.debug import print_compact_stack from model.bonds import bond_at_singlets from dna.generators.Z_Dna_Generator import Z_Dna_Generator class Z_Dna_PAM5_Generator(Z_Dna_Generator): """ Provides a PAM5 reduced model of the Z form of DNA. @attention: This class is not implemented yet. """ pass
NanoCAD-master
cad/src/dna/generators/Z_Dna_PAM5_Generator.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ DnaDuplex.py -- DNA duplex generator helper classes, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env from platform_dependent.PlatformDependent import find_plugin_dir from utilities.Log import orangemsg basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) from dna.generators.A_Dna_Generator import A_Dna_Generator class A_Dna_PAM5_Generator(A_Dna_Generator): """ Provides a PAM5 reduced model of the B form of DNA. @attention: This class is not implemented yet. """ model = "PAM5"
NanoCAD-master
cad/src/dna/generators/A_Dna_PAM5_Generator.py
NanoCAD-master
cad/src/dna/generators/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ B_Dna_Generator.py -- DNA duplex generator helper classes, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env from platform_dependent.PlatformDependent import find_plugin_dir from utilities.Log import orangemsg from dna.model.Dna_Constants import getDuplexBasesPerTurn from model.elements import PeriodicTable Element_Ae3 = PeriodicTable.getElement('Ae3') from dna.model.Dna_Constants import dnaDict basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) RIGHT_HANDED = -1 from dna.generators.Dna_Generator import Dna_Generator class B_Dna_Generator(Dna_Generator): """ Provides an atomistic model of the B form of DNA. """ form = "B-DNA" baseRise = dnaDict['B-DNA']['DuplexRise'] handedness = RIGHT_HANDED basesPerTurn = getDuplexBasesPerTurn('B-DNA') pass
NanoCAD-master
cad/src/dna/generators/B_Dna_Generator.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ DnaDuplex.py -- DNA duplex generator helper classes, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env import os from math import sin, cos, pi from utilities.debug import print_compact_traceback, print_compact_stack from platform_dependent.PlatformDependent import find_plugin_dir from files.mmp.files_mmp import readmmp from geometry.VQT import Q, V, angleBetween, cross, vlen from utilities.Log import orangemsg from utilities.exception_classes import PluginBug from utilities.constants import gensym from utilities.prefs_constants import dnaDefaultStrand1Color_prefs_key from utilities.prefs_constants import dnaDefaultStrand2Color_prefs_key from utilities.prefs_constants import dnaDefaultSegmentColor_prefs_key from dna.model.Dna_Constants import getDuplexBasesPerTurn ##from dna.updater.dna_updater_prefs import pref_dna_updater_convert_to_PAM3plus5 from simulation.sim_commandruns import adjustSinglet from model.elements import PeriodicTable from model.Line import Line from model.chem import Atom_prekill_prep Element_Ae3 = PeriodicTable.getElement('Ae3') from dna.model.Dna_Constants import basesDict, dnaDict from dna.model.dna_model_constants import LADDER_END0 basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) RIGHT_HANDED = -1 LEFT_HANDED = 1 from geometry.VQT import V, Q, norm, cross from geometry.VQT import vlen from Numeric import dot from utilities.debug import print_compact_stack from model.bonds import bond_at_singlets from dna.generators.Dna_Generator import Dna_Generator class Z_Dna_Generator(Dna_Generator): """ Provides an atomistic model of the Z form of DNA. """ form = "Z-DNA" baseRise = dnaDict['Z-DNA']['DuplexRise'] handedness = LEFT_HANDED
NanoCAD-master
cad/src/dna/generators/Z_Dna_Generator.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ DnaDuplex.py -- DNA duplex generator helper classes, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env import os from math import sin, cos, pi from utilities.debug import print_compact_traceback, print_compact_stack from platform_dependent.PlatformDependent import find_plugin_dir from files.mmp.files_mmp import readmmp from geometry.VQT import Q, V, angleBetween, cross, vlen from utilities.Log import orangemsg from utilities.exception_classes import PluginBug from utilities.constants import gensym from utilities.prefs_constants import dnaDefaultStrand1Color_prefs_key from utilities.prefs_constants import dnaDefaultStrand2Color_prefs_key from utilities.prefs_constants import dnaDefaultSegmentColor_prefs_key from dna.model.Dna_Constants import getDuplexBasesPerTurn ##from dna.updater.dna_updater_prefs import pref_dna_updater_convert_to_PAM3plus5 from simulation.sim_commandruns import adjustSinglet from model.elements import PeriodicTable from model.Line import Line from model.chem import Atom_prekill_prep Element_Ae3 = PeriodicTable.getElement('Ae3') from dna.model.Dna_Constants import basesDict, dnaDict from dna.model.dna_model_constants import LADDER_END0 basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) RIGHT_HANDED = -1 LEFT_HANDED = 1 from geometry.VQT import V, Q, norm, cross from geometry.VQT import vlen from Numeric import dot from utilities.debug import print_compact_stack from model.bonds import bond_at_singlets from dna.generators.B_Dna_Generator import B_Dna_Generator class B_Dna_PAM5_Generator(B_Dna_Generator): """ Provides a PAM5 reduced model of the B form of DNA. """ model = "PAM5" def _isStartPosition(self, index): """ Returns True if I{index} points the first base-pair position (5'). @param index: Base-pair index. @type index: int @return: True if index is zero. @rtype : bool """ if index == 0: return True else: return False def _isEndPosition(self, index): """ Returns True if I{index} points the last base-pair position (3'). @param index: Base-pair index. @type index: int @return: True if index is zero. @rtype : bool """ if index == self.getNumberOfBasePairs() - 1: return True else: return False def _strandAinfo(self, index): """ Returns parameters needed to add a base, including its complement base, to strand A. @param index: Base-pair index. @type index: int """ zoffset = 0.0 thetaOffset = 0.0 basename = "MiddleBasePair" if self._isStartPosition(index): basename = "StartBasePair" if self._isEndPosition(index): basename = "EndBasePair" if self.getNumberOfBasePairs() == 1: basename = "SingleBasePair" basefile = self._baseFileName(basename) return (basefile, zoffset, thetaOffset) def _postProcess(self, baseList): # bruce 070414 """ Set bond direction on the backbone bonds. @param baseList: List of basepair chunks that make up the duplex. @type baseList: list """ # This implem depends on the specifics of how the end-representations # are terminated. If that's changed, it might stop working or it might # start giving wrong results. In the current representation, # baseList[0] (a chunk) has two bonds whose directions we must set, # which will determine the directions of their strands: # Ss5 -> Sh5, and Ss5 <- Pe5. # Just find those bonds and set the strand directions (until such time # as they can be present to start with in the end1 mmp file). # (If we were instead passed all the atoms, we could be correct if we # just did this to the first Pe5 and Sh5 we saw, or to both of each if # setting the same direction twice is allowed.) atoms = baseList[0].atoms.values() Pe_list = filter( lambda atom: atom.element.symbol in ('Pe5'), atoms) Sh_list = filter( lambda atom: atom.element.symbol in ('Sh5'), atoms) if len(Pe_list) == len(Sh_list) == 1: for atom in Pe_list: assert len(atom.bonds) == 1 atom.bonds[0].set_bond_direction_from(atom, 1, propogate = True) for atom in Sh_list: assert len(atom.bonds) == 1 atom.bonds[0].set_bond_direction_from(atom, -1, propogate = True) else: #bruce 070604 mitigate bug in above code when number of bases == 1 # by not raising an exception when it fails. msg = "Warning: strand not terminated, bond direction not set \ (too short)" env.history.message( orangemsg( msg)) # Note: It turns out this bug is caused by a bug in the rest of the # generator (which I didn't try to diagnose) -- for number of # bases == 1 it doesn't terminate the strands, so the above code # can't find the termination atoms (which is how it figures out # what to do without depending on intimate knowledge of the base # mmp file contents). # print "baseList = %r, its len = %r, atoms in [0] = %r" % \ # (baseList, len(baseList), atoms) ## baseList = [<molecule 'unknown' (11 atoms) at 0xb3d6f58>], ## its len = 1, atoms in [0] = [Ax1, X2, X3, Ss4, Pl5, X6, X7, Ss8, Pl9, X10, X11] # It would be a mistake to fix this here (by giving it that # intimate knowledge) -- instead we need to find and fix the bug # in the rest of generator when number of bases == 1. return def _create_atomLists_for_regrouping(self, dnaGroup): """ Creates and returns the atom lists that will be used to regroup the chunks within the DnaGroup. @param dnaGroup: The DnaGroup whose atoms will be filtered and put into individual strand A or strandB or axis atom lists. @return: Returns a tuple containing three atom lists -- two atom lists for strand chunks and one for axis chunk. @see: self._regroup() """ _strandA_list = [] _strandB_list = [] _axis_list = [] # Build strand and chunk atom lists. for m in dnaGroup.members: for atom in m.atoms.values(): if atom.element.symbol in ('Pl5', 'Pe5'): if atom.getDnaStrandId_for_generators() == 'Strand1': _strandA_list.append(atom) # Following makes sure that the info record #'dnaStrandId_for_generators' won't be written for #this atom that the dna generator outputs. i.e. #the info record 'dnaStrandId_for_generators' is only #required while generating the dna from scratch #(by reading in the strand base files in 'cad/plugins' #see more comments in Atom.getDnaStrandId_for_generators atom.setDnaStrandId_for_generators('') elif atom.getDnaStrandId_for_generators() == 'Strand2': atom.setDnaStrandId_for_generators('') _strandB_list.append(atom) if atom.element.symbol in ('Ss5', 'Sh5'): if atom.getDnaBaseName() == 'a': _strandA_list.append(atom) #Now reset the DnaBaseName for the added atom # to 'unassigned' base i.e. 'X' atom.setDnaBaseName('X') elif atom.getDnaBaseName() == 'b': _strandB_list.append(atom) #Now reset the DnaBaseName for the added atom # to 'unassigned' base i.e. 'X' atom.setDnaBaseName('X') else: msg = "Ss5 or Sh5 atom not assigned to strand 'a' or 'b'." raise PluginBug(msg) elif atom.element.symbol in ('Ax5', 'Ae5', 'Gv5', 'Gr5'): _axis_list.append(atom) return (_strandA_list, _strandB_list, _axis_list)
NanoCAD-master
cad/src/dna/generators/B_Dna_PAM5_Generator.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ A_Dna_Generator.py -- DNA duplex generator helper class, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env from platform_dependent.PlatformDependent import find_plugin_dir from utilities.Log import orangemsg from dna.model.Dna_Constants import dnaDict basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) RIGHT_HANDED = -1 from dna.generators.Dna_Generator import Dna_Generator class A_Dna_Generator(Dna_Generator): """ Provides an atomistic model of the A form of DNA. The geometry for A-DNA is very twisty and funky. We need to to research the A form since it's not a simple helix (like B) or an alternating helix (like Z). @attention: This class is not implemented yet. """ form = "A-DNA" baseRise = dnaDict['A-DNA']['DuplexRise'] handedness = RIGHT_HANDED
NanoCAD-master
cad/src/dna/generators/A_Dna_Generator.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ DnaDuplex.py -- DNA duplex generator helper classes, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env import os from math import sin, cos, pi from utilities.debug import print_compact_traceback, print_compact_stack from platform_dependent.PlatformDependent import find_plugin_dir from files.mmp.files_mmp import readmmp from geometry.VQT import Q, V, angleBetween, cross, vlen from utilities.Log import orangemsg from utilities.exception_classes import PluginBug from utilities.constants import gensym from utilities.prefs_constants import dnaDefaultStrand1Color_prefs_key from utilities.prefs_constants import dnaDefaultStrand2Color_prefs_key from utilities.prefs_constants import dnaDefaultSegmentColor_prefs_key from dna.model.Dna_Constants import getDuplexBasesPerTurn ##from dna.updater.dna_updater_prefs import pref_dna_updater_convert_to_PAM3plus5 from simulation.sim_commandruns import adjustSinglet from model.elements import PeriodicTable from model.Line import Line from model.chem import Atom_prekill_prep Element_Ae3 = PeriodicTable.getElement('Ae3') from dna.model.Dna_Constants import basesDict, dnaDict from dna.model.dna_model_constants import LADDER_END0 basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) RIGHT_HANDED = -1 LEFT_HANDED = 1 from geometry.VQT import V, Q, norm, cross from geometry.VQT import vlen from Numeric import dot from utilities.debug import print_compact_stack from model.bonds import bond_at_singlets from dna.generators.Z_Dna_Generator import Z_Dna_Generator class Z_Dna_Atomistic_Generator(Z_Dna_Generator): """ Provides an atomistic model of the Z form of DNA. @attention: This class will never be implemented. """ model = "PAM5" def _strandAinfo(self, baseLetter, index): """ Returns parameters needed to add a base to strand A. @param baseLetter: The base letter. @type baseLetter: str @param index: Base-pair index. @type index: int """ thetaOffset = 0.0 basename = basesDict[baseLetter]['Name'] if (index & 1) != 0: # Index is odd. basename += "-outer" zoffset = 2.045 else: # Index is even. basename += '-inner' zoffset = 0.0 basefile = self._baseFileName(basename) return (basefile, zoffset, thetaOffset) def _strandBinfo(self, baseLetter, index): """ Returns parameters needed to add a base to strand B. @param baseLetter: The base letter. @type baseLetter: str @param index: Base-pair index. @type index: int """ thetaOffset = 0.5 * pi basename = basesDict[baseLetter]['Name'] if (index & 1) != 0: basename += '-inner' zoffset = -0.055 else: basename += "-outer" zoffset = -2.1 basefile = self._baseFileName(basename) return (basefile, zoffset, thetaOffset)
NanoCAD-master
cad/src/dna/generators/Z_Dna_Atomistic_Generator.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ DnaDuplex.py -- DNA duplex generator helper classes, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env from utilities.debug import print_compact_stack from platform_dependent.PlatformDependent import find_plugin_dir from geometry.VQT import Q, cross, vlen from utilities.Log import orangemsg from utilities.exception_classes import PluginBug from simulation.sim_commandruns import adjustSinglet from model.elements import PeriodicTable Element_Ae3 = PeriodicTable.getElement('Ae3') basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) RIGHT_HANDED = -1 LEFT_HANDED = 1 from geometry.VQT import norm from Numeric import dot from dna.generators.B_Dna_Generator import B_Dna_Generator class B_Dna_PAM3_Generator(B_Dna_Generator): """ Provides a PAM3 reduced model of the B form of DNA. """ model = "PAM3" strandA_atom_end1 = None def _strandAinfo(self, index): """ Returns parameters needed to add the next base-pair to the duplex build built. @param index: Base-pair index. @type index: int """ zoffset = 0.0 thetaOffset = 0.0 basename = "MiddleBasePair" basefile = self._baseFileName(basename) return (basefile, zoffset, thetaOffset) def _postProcess(self, baseList): """ Final tweaks on the DNA chunk, including: - Transmute Ax3 atoms on each end into Ae3. - Adjust open bond singlets. @param baseList: List of basepair chunks that make up the duplex. @type baseList: list @note: baseList must contain at least two base-pair chunks. """ if len(baseList) < 1: print_compact_stack("bug? (ignoring) DnaDuplex._postProcess called but "\ "baseList is empty. Maybe dna_updater was "\ "run?: ") return start_basepair_atoms = baseList[0].atoms.values() end_basepair_atoms = baseList[-1].atoms.values() Ax_caps = filter( lambda atom: atom.element.symbol in ('Ax3'), start_basepair_atoms) Ax_caps += filter( lambda atom: atom.element.symbol in ('Ax3'), end_basepair_atoms) # Transmute Ax3 caps to Ae3 atoms. # Note: this leaves two "killed singlets" hanging around, # one from each Ax3 cap. # # REVIEW: is it safe to simply not do this when dna_updater_is_enabled()? # [bruce 080320 question] for atom in Ax_caps: atom.Transmute(Element_Ae3) # X_List will contain 6 singlets, 2 of which are killed (non-bonded). # The other 4 are the 2 pair of strand open bond singlets. X_List = filter( lambda atom: atom.element.symbol in ('X'), start_basepair_atoms) X_List += filter( lambda atom: atom.element.symbol in ('X'), end_basepair_atoms) # Adjust the 4 open bond singlets. for singlet in X_List: if singlet.killed(): # Skip the 2 killed singlets. continue adjustSinglet(singlet) return def _determine_axis_and_strandA_endAtoms_at_end_1(self, chunk): """ Determine the axis end atom and the strand atom on strand 1 connected to it , at end1 . i.e. the first mouse click point from which user started drawing the dna duplex (rubberband line) These are initially set to None. The strand base atom of Strand-A, connected to the self.axis_atom_end1 The vector between self.axis_atom_end1 and self.strandA_atom_end1 is used to determine the final orientation of the created duplex done in self._orient_to_position_first_strandA_base_in_axis_plane() This vector is aligned such that it is parallel to the screen. i.e. StrandA end Atom and corresponding axis end atom are coplaner and parallel to the screen. @NOTE:The caller should make sure that the appropriate chunk is passed as an argument to this method. This function itself only finds and assigns the axis ('Ax3') and strand ('Ss3' atom and on StrandA) atoms it sees first to the respective attributes. (and which pass other necessary tests) @see: self.make() where this function is called @see: self._orient_to_position_first_strandA_base_in_axis_plane() """ for atm in chunk.atoms.itervalues(): if self.axis_atom_end1 is None: if atm.element.symbol == 'Ax3': self.axis_atom_end1 = atm if self.strandA_atom_end1 is None: if atm.element.symbol == 'Ss3' and atm.getDnaBaseName() == 'a': self.strandA_atom_end1 = atm def _orient_for_modify(self, end1, end2): """ Orient the new dna to match up appropriately with the original dna (being modified/resized) """ b = norm(end2 - end1) new_ladder = self.axis_atom_end1.molecule.ladder new_ladder_end = new_ladder.get_ladder_end(self.axis_atom_end1) chunkListForRotation = new_ladder.all_chunks() #This method fixes bug 2889. See that method for more comments. self._redetermine_resizeEndStrand1Atom_and_strandA_atom_end1() axis_strand_vector = (self.strandA_atom_end1.posn() - \ self.axis_atom_end1.posn()) vectorAlongLadderStep = self._resizeEndStrand1Atom.posn() - \ self._resizeEndAxisAtom.posn() unitVectorAlongLadderStep = norm(vectorAlongLadderStep) self.final_pos_strand_end_atom = \ self.axis_atom_end1.posn() + \ vlen(axis_strand_vector)*unitVectorAlongLadderStep q_new = Q(axis_strand_vector, vectorAlongLadderStep) if dot(axis_strand_vector, cross(vectorAlongLadderStep, b)) < 0: q_new2 = Q(b, -q_new.angle) else: q_new2 = Q(b, q_new.angle) self.assy.rotateSpecifiedMovables(q_new2, chunkListForRotation, end1) def _redetermine_resizeEndStrand1Atom_and_strandA_atom_end1(self): """ @ATTENTION: The strandA endatom at end1 is modified in this method. It is originally computed in self._determine_axis_and_strandA_endAtoms() The recomputation is done to fix bug 2889 (for v1.1.0). See B_Dna_PAM3_Generator.orient_for_modify() for details. This NEEDS CLEANUP @see: self._create_raw_duplex() @see: self.orient_for_modify() """ #Method created just before codefreeze for v1.1.0 to fix newly discovered #bug 2889 -- Ninad 2008-06-02 #Perhaps computing this strand atom always be done at a later #stage (like done in here). But not sure if this will cause any bugs. #So not changing the original implementation . new_ladder = self.axis_atom_end1.molecule.ladder endBaseAtomList = new_ladder.get_endBaseAtoms_containing_atom(self.axis_atom_end1) endStrandbaseAtoms = (endBaseAtomList[0], endBaseAtomList[2]) self.strandA_atom_end1 = None #Check if the resizeEndStrandAtom is a 5' or a 3' end. #If it is a 5' or 3' end, then chose the strand end atom of the #new duplex such that it is the opposite of it (i.e. if resizeEndStrandAtom #is a 5' end, the strand end atom on new duplex should be chosen such that #its a 3' end. Using these references, we will orient the new duplex #to match up correctly with the resizeEnd strand atom (and later #the old and new dnas will be bonded at these ends) #However, if the chosen resizeEndStrandAtom of original duplex #doesn't have a 5' or 3' end, then we will choose the second #resizeEndStrandEndAtom on the original duplex and do the same #computations resizeEndStrandAtom_isFivePrimeEndAtom = False resizeEndStrandAtom_isThreePrimeEndAtom = False if self._resizeEndStrand1Atom.isFivePrimeEndAtom(): resizeEndStrandAtom_isFivePrimeEndAtom = True elif self._resizeEndStrand1Atom.isThreePrimeEndAtom(): resizeEndStrandAtom_isThreePrimeEndAtom = True if not (resizeEndStrandAtom_isFivePrimeEndAtom or \ resizeEndStrandAtom_isThreePrimeEndAtom): if self._resizeEndStrand2Atom: if self._resizeEndStrand2Atom.isFivePrimeEndAtom(): resizeEndStrandAtom_isFivePrimeEndAtom = True elif self._resizeEndStrand2Atom.isThreePrimeEndAtom(): resizeEndStrandAtom_isThreePrimeEndAtom = True if (resizeEndStrandAtom_isFivePrimeEndAtom or \ resizeEndStrandAtom_isThreePrimeEndAtom): #Swap resizeEndStrand1Atom and resizeEndStrand2Atom atm1, atm2 = self._resizeEndStrand1Atom, self._resizeEndStrand2Atom self._resizeEndStrand1Atom, self._resizeEndStrand2Atom = atm2, atm1 for atm in endStrandbaseAtoms: if atm is not None: if atm.isThreePrimeEndAtom() and \ resizeEndStrandAtom_isFivePrimeEndAtom: self.strandA_atom_end1 = atm break elif atm.isFivePrimeEndAtom() and \ resizeEndStrandAtom_isThreePrimeEndAtom: self.strandA_atom_end1 = atm break if self.strandA_atom_end1 is None: #As a fallback, set this atom to any atom in endStrandbaseAtoms #but, this may cause a bug in which bond directions are not #properly set. for atm in endStrandbaseAtoms: if atm is not None: self.strandA_atom_end1 = atm def _orient_to_position_first_strandA_base_in_axis_plane(self, baseList, end1, end2): """ The self._orient method orients the DNA duplex parallel to the screen (lengthwise) but it doesn't ensure align the vector through the strand end atom on StrandA and the corresponding axis end atom (at end1) , parallel to the screen. This function does that ( it has some rare bugs which trigger where it doesn't do its job but overall works okay ) What it does: After self._orient() is done orienting, it finds a Quat that rotates between the 'desired vector' between strand and axis ends at end1(aligned to the screen) and the actual vector based on the current positions of these atoms. Using this quat we rotate all the chunks (as a unit) around a common center. @BUG: The last part 'rotating as a unit' uses a readymade method in ops_motion.py -- 'rotateSpecifiedMovables' . This method itself may have some bugs because the axis of the dna duplex is slightly offset to the original axis. @see: self._determine_axis_and_strandA_endAtoms_at_end_1() @see: self.make() """ #the vector between the two end points. these are more likely #points clicked by the user while creating dna duplex using endpoints #of a line. In genral, end1 and end2 are obtained from self.make() b = norm(end2 - end1) axis_strand_vector = (self.strandA_atom_end1.posn() - \ self.axis_atom_end1.posn()) vectorAlongLadderStep = cross(-self.assy.o.lineOfSight, b) unitVectorAlongLadderStep = norm(vectorAlongLadderStep) self.final_pos_strand_end_atom = \ self.axis_atom_end1.posn() + \ vlen(axis_strand_vector)*unitVectorAlongLadderStep expected_vec = self.final_pos_strand_end_atom - self.axis_atom_end1.posn() q_new = Q(axis_strand_vector, expected_vec) if dot(axis_strand_vector, self.assy.o.lineOfSight) < 0: q_new2 = Q(b, -q_new.angle) else: q_new2 = Q(b, q_new.angle) self.assy.rotateSpecifiedMovables(q_new2, baseList, end1) def _strand_neighbors_to_delete(self, axisAtom): """ Returns a list of strand neighbors of the given axis atom to delete from the original dna being resized (and resizing will result in removing bases/ basepairs from the dna). This method determines whether both the strand neigbors of this axisAtom need to be deleted or is it just a single strand neighbor on a specific Dna ladder needs to be deleted. The latter is the case while resizing a single strand of a Dna. @see: self._remove_bases_from_dna() where this is called. @see: Dna._strand_neighbors_to_delete() -- overridden here @see: B_Dna_PAM3_Generator_SingleStrand._strand_neighbors_to_delete() which overrides this method """ strand_neighbors_to_delete = axisAtom.strand_neighbors() return strand_neighbors_to_delete def _create_atomLists_for_regrouping(self, dnaGroup): """ Creates and returns the atom lists that will be used to regroup the chunks within the DnaGroup. @param dnaGroup: The DnaGroup whose atoms will be filtered and put into individual strand A or strandB or axis atom lists. @return: Returns a tuple containing three atom lists -- two atom lists for strand chunks and one for axis chunk. @see: self._regroup() """ _strandA_list = [] _strandB_list = [] _axis_list = [] # Build strand and chunk atom lists. for m in dnaGroup.members: for atom in m.atoms.values(): if atom.element.symbol in ('Ss3'): if atom.getDnaBaseName() == 'a': _strandA_list.append(atom) #Now reset the DnaBaseName for the added atom # to 'unassigned' base i.e. 'X' atom.setDnaBaseName('X') elif atom.getDnaBaseName() == 'b': _strandB_list.append(atom) #Now reset the DnaBaseName for the added atom # to 'unassigned' base i.e. 'X' atom.setDnaBaseName('X') else: msg = "Ss3 atom not assigned to strand 'a' or 'b'." raise PluginBug(msg) elif atom.element.symbol in ('Ax3', 'Ae3'): _axis_list.append(atom) return (_strandA_list, _strandB_list, _axis_list)
NanoCAD-master
cad/src/dna/generators/B_Dna_PAM3_Generator.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ DnaDuplex.py -- DNA duplex generator helper classes, based on empirical data. @author: Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Mark 2007-10-18: - Created. Major rewrite of DnaGenHelper.py. """ import foundation.env as env import os from math import sin, cos, pi from utilities.debug import print_compact_traceback, print_compact_stack from platform_dependent.PlatformDependent import find_plugin_dir from files.mmp.files_mmp import readmmp from geometry.VQT import Q, V, angleBetween, cross, vlen from commands.Fuse.fusechunksMode import fusechunksBase from utilities.Log import orangemsg from utilities.exception_classes import PluginBug from utilities.constants import gensym from utilities.prefs_constants import dnaDefaultStrand1Color_prefs_key from utilities.prefs_constants import dnaDefaultStrand2Color_prefs_key from utilities.prefs_constants import dnaDefaultSegmentColor_prefs_key from dna.model.Dna_Constants import getDuplexBasesPerTurn ##from dna.updater.dna_updater_prefs import pref_dna_updater_convert_to_PAM3plus5 from simulation.sim_commandruns import adjustSinglet from model.elements import PeriodicTable from model.Line import Line from model.chem import Atom_prekill_prep Element_Ae3 = PeriodicTable.getElement('Ae3') from dna.model.Dna_Constants import basesDict, dnaDict from dna.model.dna_model_constants import LADDER_END0 basepath_ok, basepath = find_plugin_dir("DNA") if not basepath_ok: env.history.message(orangemsg("The cad/plugins/DNA directory is missing.")) RIGHT_HANDED = -1 LEFT_HANDED = 1 from geometry.VQT import V, Q, norm, cross from geometry.VQT import vlen from Numeric import dot from utilities.debug import print_compact_stack from model.bonds import bond_at_singlets class Dna_Generator: """ Dna_Generator base class. It is inherited by B_Dna and Z_Dna subclasses. @ivar baseRise: The rise (spacing) between base-pairs along the helical (Z) axis. @type baseRise: float @ivar handedness: Right-handed (B and A forms) or left-handed (Z form). @type handedness: int @ivar model: The model representation, where: - "PAM3" = PAM3 reduced model. - "PAM5" = PAM5 reduced model. @type model: str @ivar numberOfBasePairs: The number of base-pairs in the duplex. @type numberOfBasePairs: int @note: Atomistic models are not supported. @TODO: This classe's attribute 'assy' (self.assy) is determined in self.make Its okay because callers only call dna.make() first. If assy object is going to remain constant,(hopefully is the case) the caller should pass it to the costructor of this class. (not defined as of 2008-03-17. """ #initialize sel.assy to None. This is determined each time in self.make() #using the 'group' argument of that method. assy = None #The following is a list bases inserted in to the model while generating #dna. see self.make() baseList = [] strandA_atom_end1 = None def modify(self, group, resizeEndAxisAtom, numberOfBasePairs, basesPerTurn, duplexRise, endPoint1, endPoint2 , resizeEndStrandAtom = None ): """ Modify the original (double or single stranded) dna with the new dna. It creats a raw dna (single or double stranded) OR removes bases from the oridinal dna if resizing operation is to lengthen or shorten the original dna respctively. If it is lengthening operation, then after creating a raw duplex it does a basic orientation to align new dna axis with original one and then a final orientation to make the end strand and axis atoms fusable with the resize end. AVAILABLE AS A DEBUG PREFERENCE ONLY AS OF 2008-04-02. NEED CLEANUP , LOTS OF DOCUMENTATION AND RENAMING. @see: self._fuse_new_dna_with_original_duplex @see: self.orient_for_modify() @see: B-Dna_PAM3_singleStrand TODO: - the optional argument resizeEndStrandAtom and assignment of self.resizeEndStrand1Atom needs to be cleaned up. - refactoring cleanup and more renaming etc planned post FNANO - See also comments in B_Dna_PAM3_SingleStrand_Generator """ self.assy = group.assy assy = group.assy #Make sure to clear self.baseList each time self.modify() is called self.baseList = [] self.setNumberOfBasePairs(abs(numberOfBasePairs)) self.setBaseRise(duplexRise) #@TODO: See a note in DnaSegment_EditCommand._createStructure(). Should #the parentGroup object <group> be assigned properties such as #duplexRise, basesPerTurn in this method itself? to be decided self.setBasesPerTurn(basesPerTurn) #End axis atom at end1. i.e. the first mouse click point from which #user started resizing the dna duplex (rubberband line). This is initially #set to None. When we start creating the duplex and read in the first #mmp file: MiddleBasePair.mmp, we assign the appropriate atom to this #variable. See self._determine_axis_and_strandA_endAtoms_at_end_1() self.axis_atom_end1 = None #The strand base atom of Strand-A, connected to the self.axis_atom_end1 #The vector between self.axis_atom_end1 and self.strandA_atom_end1 #is used to determine the final orientation of the created duplex. #that aligns this vector such that it is parallel to the screen. #see self._orient_to_position_first_strandA_base_in_axis_plane() for #more details. self.strandA_atom_end1 = None #The end strand base-atom of the original structure (segment) being #resized. This and the corresponding axis end atom ot the original #structure will be used to orient the new bases we will create and fuse #to the original structure. self._resizeEndStrand1Atom = resizeEndStrandAtom #The axis end base atom of the original structure (at the resize end) self._resizeEndAxisAtom = None #Do a safety check. If number of base pairs to add or subtract is 0, #don't proceed further. if numberOfBasePairs == 0: print "Duplex not created. The number of base pairs are unchanged" return #If the number of base pairs supplied by the caller are negative, it #means the caller wants to delete those from the original structure #(duplex). if numberOfBasePairs < 0: numberOfBasePairsToRemove = abs(numberOfBasePairs) self._remove_bases_from_dna(group, resizeEndAxisAtom, numberOfBasePairsToRemove) return #Create a raw duplex first in Z direction. Using reference mmp basefiles #Later we will reorient this duplex and then fuse it with the original #duplex (which is being resized) self._create_raw_duplex(group, numberOfBasePairs, basesPerTurn, duplexRise ) # Orient the duplex. #Do the basic orientation so that axes of the newly created raw duplex #aligns with the original duplex self._orient(self.baseList, resizeEndAxisAtom.posn(), endPoint2) #Now determine the the strand1-end and axis-endAtoms at the resize #end of the *original structure*. We will use this information #for final orientation of the new duplex and also for fusing the new #duplex with the original one. #find out dna ladder to which the end axis atom of the original duplex #belongs to ladder = resizeEndAxisAtom.molecule.ladder #list of end base atoms of the original duplex, at the resize end. #This list includes the axis end atom and strand end base atoms #(so for a double stranded dna, this will return 3 atoms whereas #for a single stranded dna, it will return 2 atoms endBaseAtomList = ladder.get_endBaseAtoms_containing_atom(resizeEndAxisAtom) #As of 2008-03-26, we support onlu double stranded dna case #So endBaseAtomList should have atleast 3 atoms to proceed further. if endBaseAtomList and len(endBaseAtomList) > 2: if not resizeEndStrandAtom: self._resizeEndStrand1Atom = endBaseAtomList[0] self._resizeEndAxisAtom = endBaseAtomList[1] self._resizeEndStrand2Atom = None if endBaseAtomList[2] not in (None, self._resizeEndStrand1Atom): self._resizeEndStrand2Atom = endBaseAtomList[2] #Run full dna update so that the newly created duplex represents #one in dna data model. Do it before calling self._orient_for_modify #The dna updater run will help us use dna model features such as #dna ladder, rail. These will be used in final orientation #of the new duplex and later fusing it with the original duplex #REVIEW: Wheather dna updater should be run without #calling assy.update_parts... i.e. only running a local update #than the whole on -- Ninad 2008-03-26 self.assy.update_parts() #Do the final orientation of the new duplex. i.e rotate the new #duplex around its own axis such that its then fusable with the #original duplex. self._orient_for_modify(endPoint1, endPoint2) #new_ladder is the dna ladder of the newly generated duplex. new_ladder = self.axis_atom_end1.molecule.ladder #REFACTOR: Reset the dnaBaseNames of the atoms to 'X' #replacing the original dnaBaseNames 'a' or 'b'. Do not do it #inside self._postProcess because that method is also used by #self.make that calls self._create_atomLists_for_regrouping #after calling self._postProcess for m in new_ladder.all_chunks(): for atm in m.atoms.values(): if atm.element.symbol in ('Ss3') and atm.getDnaBaseName() in ('a','b'): atm.setDnaBaseName('X') #Find out the 'end' of the new ladder i.e. whether it is end0 or #end1, that contains the first end axis base atom of the new duplex #i.e. atom self.axis_atom_end1) new_ladder_end = new_ladder.get_ladder_end(self.axis_atom_end1) #Find out three the end base atoms list of the new duplex endBaseAtomList_generated_duplex = new_ladder.get_endBaseAtoms_containing_atom(self.axis_atom_end1) #strandA atom should be first in the list. If it is not, #make sure that this list includes end atoms in this order: #[strand1, axis, strand2] if self.strandA_atom_end1 in endBaseAtomList_generated_duplex and \ self.strandA_atom_end1 != endBaseAtomList_generated_duplex[0]: endBaseAtomList_generated_duplex.reverse() #Note that after orienting the duplex the first set of end base atoms #in endBaseAtomList_generated_duplex will be killed. Why? because #the corrsponding atoms are already present on the original duplex #We just used this new set for proper orientation. #As we will be deleting the first set of #endBaseAtomList_generated_duplex, et a set of base atoms connected #to) the end base atoms in endBaseAtomList_generated_duplex. This #will become our new end base atoms new_endBaseAtomList = [] for atm in endBaseAtomList_generated_duplex: if atm is not None: rail = atm.molecule.get_ladder_rail() baseindex = rail.baseatoms.index(atm) next_atm = None if len(rail.baseatoms) == 1: for bond_direction in (1, -1): next_atm = atm.next_atom_in_bond_direction(bond_direction) else: if new_ladder_end == 0: #@@@BUG 2008-03-21. Handle special case when len(rail.baseatoms == 1) next_atm = rail.baseatoms[1] elif new_ladder_end == 1: next_atm = rail.baseatoms[-2] assert next_atm is not None new_endBaseAtomList.append(next_atm) DEBUG_FUSE = True if DEBUG_FUSE: #@@REVIEW This doesn't invalidate the ladder. We just delete #all the atoms and then the dna updater runs. for atm in endBaseAtomList_generated_duplex: if atm is not None: atm.kill() #Run dna updater again self.assy.update_parts() self.axis_atom_end1 = None self._fuse_new_dna_with_original_duplex(new_endBaseAtomList, endBaseAtomList) self.assy.update_parts() def _replace_overlapping_axisAtoms_of_new_dna(self, new_endBaseAtomList): """ @see: B_Dna_PAM3_SingleStrand_Generator._replace_overlapping_axisAtoms_of_new_dna() """ pass def _bond_bare_strandAtoms_with_orig_axisAtoms(self, new_endBaseAtomList): pass def _fuse_new_dna_with_original_duplex(self, new_endBaseAtomList, endBaseAtomList): """ Fuse the new dna strand (and axxis) end atom to the original dna TODO: method needs to be renamed The original dna may be a single stranded dna or a duplex. Until 2008-04-02 ,it was possible to create or modify only a duplex and thats why the name 'duplex' @see: self.modify() @see: B_Dna_PAM3_SingleStrand_Generator._fuse_new_dna_with_original_duplex() """ #FUSE new duplex with the original duplex #strand1 chunks chunkList1 = \ [ new_endBaseAtomList[0].molecule, self._resizeEndStrand1Atom.molecule] #Axis chunks chunkList2 = \ [ new_endBaseAtomList[1].molecule, self._resizeEndAxisAtom.molecule] if endBaseAtomList[2]: #strand2 chunks chunkList3 = \ [new_endBaseAtomList[2].molecule, endBaseAtomList[2].molecule] else: chunkList3 = [] #Set the chunk color and chunk display of the new duplex such that #it matches with the original duplex chunk color and display #Actually, fusing the chunks should have taken care of this, but #for some unknown reasons, its not happening. May be because #chunks are not 'merged'? ... Setting display and color for new #duplex chunk is explicitely done below. Fixes bug 2711 for chunkPair in (chunkList1, chunkList2, chunkList3): if chunkPair: display = chunkPair[1].display color = chunkPair[1].color chunkPair[0].setDisplayStyle(display) if color: chunkPair[0].setcolor(color) #Original implementation which relied on on fuse chunks for finding #bondable atom pairs within a tolerance limit. This is no longer #used and can be removed after more testing of explicit bonding #done in self._bond_atoms_in_atomPairs() (called below) #-- Ninad 2008-04-14 ##self.fuseBasePairChunks(chunkList1) ##self.fuseBasePairChunks(chunkList2, fuseTolerance = 1.5) ##if chunkList3: ##self.fuseBasePairChunks(chunkList3) strandPairsToBond = [ (new_endBaseAtomList[0], self._resizeEndStrand1Atom)] if endBaseAtomList[2]: strandPairsToBond.append((new_endBaseAtomList[2], endBaseAtomList[2])) axisAtomPairsToBond = [ (new_endBaseAtomList[1], self._resizeEndAxisAtom)] self._bond_strandAtom_pairs(strandPairsToBond) #Create explicit bonds between the end base atoms #(like done in self._bond_bare_strandAtoms_with_orig_axisAtoms()) #instead of relying on fuse chunks (which relies on finding #bondable atom pairs within a tolerance limit. This fixes bug 2798 #-- Ninad 2008-04-14 self._bond_atoms_in_atomPairs(axisAtomPairsToBond) #Now replace the overlapping axis atoms with the corresponding #original axis atoms, make bonds between strand and axis atoms as needed #see this method docstrings for details self._replace_overlapping_axisAtoms_of_new_dna(new_endBaseAtomList) def _bond_strandAtom_pairs(self, strandPairsToBond): bondPoint1 = None bondPoint2 = None bondPoint3 = None bondPoint4 = None if len(strandPairsToBond) == 2: firstStrandAtomPair = strandPairsToBond[0] secondStrandAtomPair = strandPairsToBond[1] bondablePairs_1 = self._getBondablePairsForStrandAtoms(firstStrandAtomPair) bondablePairs_2 = self._getBondablePairsForStrandAtoms(secondStrandAtomPair) if bondablePairs_1[0] is not None and bondablePairs_2[1] is not None: bondPoint1, bondPoint2 = bondablePairs_1[0] bondPoint3, bondPoint4 = bondablePairs_2[1] elif bondablePairs_1[1] is not None and bondablePairs_2[0] is not None: bondPoint1, bondPoint2 = bondablePairs_1[1] bondPoint3, bondPoint4 = bondablePairs_2[0] elif len(strandPairsToBond) == 1: firstStrandAtomPair = strandPairsToBond[0] bondablePairs_1 = self._getBondablePairsForStrandAtoms(firstStrandAtomPair) if bondablePairs_1[0] is not None: bondPoint1, bondPoint2 = bondablePairs_1[0] elif bondablePairs_1[1] is not None: bondPoint1, bondPoint2 = bondablePairs_1[1] #Do the actual bonding if bondPoint1 and bondPoint2: bond_at_singlets(bondPoint1, bondPoint2, move = False) if bondPoint3 and bondPoint4: bond_at_singlets(bondPoint3, bondPoint4, move = False) def _getBondablePairsForStrandAtoms(self, strandAtomPair): bondablePairs = [] atm1 = strandAtomPair[0] atm2 = strandAtomPair[1] assert atm1.element.role == 'strand' and atm2.element.role == 'strand' #Initialize all possible bond points to None five_prime_bondPoint_atm1 = None three_prime_bondPoint_atm1 = None five_prime_bondPoint_atm2 = None three_prime_bondPoint_atm2 = None #Initialize the final bondPoints we will use to create bonds bondPoint1 = None bondPoint2 = None #Find 5' and 3' bondpoints of atm1 (BTW, as of 2008-04-11, atm1 is #the new dna strandend atom See self._fuse_new_dna_with_original_duplex #But it doesn't matter here. for s1 in atm1.singNeighbors(): bnd = s1.bonds[0] if bnd.isFivePrimeOpenBond(): five_prime_bondPoint_atm1 = s1 if bnd.isThreePrimeOpenBond(): three_prime_bondPoint_atm1 = s1 #Find 5' and 3' bondpoints of atm2 for s2 in atm2.singNeighbors(): bnd = s2.bonds[0] if bnd.isFivePrimeOpenBond(): five_prime_bondPoint_atm2 = s2 if bnd.isThreePrimeOpenBond(): three_prime_bondPoint_atm2 = s2 #Determine bondpoint1 and bondPoint2 (the ones we will bond). See method #docstring for details. if five_prime_bondPoint_atm1 and three_prime_bondPoint_atm2: bondablePairs.append((five_prime_bondPoint_atm1, three_prime_bondPoint_atm2 )) else: bondablePairs.append(None) #Following will overwrite bondpoint1 and bondPoint2, if the condition is #True. Doesn't matter. See method docstring to know why. if three_prime_bondPoint_atm1 and five_prime_bondPoint_atm2: bondablePairs.append((three_prime_bondPoint_atm1, five_prime_bondPoint_atm2)) else: bondablePairs.append(None) return bondablePairs def _bond_atoms_in_atomPairs(self, atomPairs): """ Create bonds between the atoms in given atom pairs. It creats explicit bonds between the two atoms at the specified bondpoints (i.e. it doesn't use fuseChunkBase to find the bondable pairs within certain tolerance) @see: self._fuse_new_dna_with_original_duplex() @see: _bond_two_strandAtoms() called here @TODO: Refactor self._bond_bare_strandAtoms_with_orig_axisAtoms self._bond_axisNeighbors_with_orig_axisAtoms to use this method """ for atm1, atm2 in atomPairs: if atm1.element.role == 'strand' and atm2.element.role == 'strand': self._bond_two_strandAtoms(atm1, atm2) else: #@REVIEW -- As of 2008-04-14, the atomPairs send to this method #are of the same type i.e. (axis, axis) or (strand, strand) #but when we do refactoring of methods like #self._bond_bare_strandAtoms_with_orig_axisAtoms, to use this #method, may be we must make sure that we are not bonding #an axis atom with a 5' or 3' bondpoint of the strand atom. #Skip the pair if its one and the same atom. #-- Ninad 2008-04-14 if atm1 is not atm2: for s1 in atm1.singNeighbors(): if atm2.singNeighbors(): s2 = atm2.singNeighbors()[0] bond_at_singlets(s1, s2, move = False) break #reposition bond points (if any) on the new dna's end axis atom #that is just bonded with the resize end axis atom of the original #duplex . #This fixes bug BUG 2928 # '1st Ax atom missing bondpoint when lengthening DnaStrand' #Note that this bug was observed only in Ax-Ax bonding. #Ss bonding is not affected. And, if we also reposition the #bondpoints for Ss atoms, the bondpoints may not be oriented #in desired way (i.e. reposition_baggage may not handle strand #bondpoint orientation well)/. For these reasons, it is only #implemented for Ax-Ax bonding. --Ninad 2008-08-22 atm1.reposition_baggage() atm2.reposition_baggage() def _bond_two_strandAtoms(self, atm1, atm2): """ Bonds the given strand atoms (sugar atoms) together. To bond these atoms, it always makes sure that a 3' bondpoint on one atom is bonded to 5' bondpoint on the other atom. Example: User lengthens a strand by a single strand baseatom. The final task done in self.modify() is to fuse the created strand base atom with the strand end atom of the original dna. But this new atom has two bondpoints -- one is a 3' bondpoint and other is 5' bondpoint. So we must find out what bondpoint is available on the original dna. If its a 5' bondpoint, we will use that and the 3'bondpoint available on the new strand baseatom. But what if even the strand endatom of the original dna is a single atom not bonded to any strand neighbors? ..thus, even that atom will have both 3' and 5' bondpoints. In that case it doesn't matter what pair (5' orig and 3' new) or (3' orig and 5' new) we bond, as long as we honor bonding within the atoms of any atom pair mentioned above. @param atm1: The first sugar atom of PAM3 (i.e. the strand atom) to be bonded with atm2. @param atm2: Second sugar atom @see: self._fuse_new_dna_with_original_duplex() @see: self._bond_atoms_in_atomPairs() which calls this """ #Moved from B_Dna_PAM3_SingleStrand_Generator to here, to fix bugs like #2711 in segment resizing-- Ninad 2008-04-14 assert atm1.element.role == 'strand' and atm2.element.role == 'strand' #Initialize all possible bond points to None five_prime_bondPoint_atm1 = None three_prime_bondPoint_atm1 = None five_prime_bondPoint_atm2 = None three_prime_bondPoint_atm2 = None #Initialize the final bondPoints we will use to create bonds bondPoint1 = None bondPoint2 = None #Find 5' and 3' bondpoints of atm1 (BTW, as of 2008-04-11, atm1 is #the new dna strandend atom See self._fuse_new_dna_with_original_duplex #But it doesn't matter here. for s1 in atm1.singNeighbors(): bnd = s1.bonds[0] if bnd.isFivePrimeOpenBond(): five_prime_bondPoint_atm1 = s1 if bnd.isThreePrimeOpenBond(): three_prime_bondPoint_atm1 = s1 #Find 5' and 3' bondpoints of atm2 for s2 in atm2.singNeighbors(): bnd = s2.bonds[0] if bnd.isFivePrimeOpenBond(): five_prime_bondPoint_atm2 = s2 if bnd.isThreePrimeOpenBond(): three_prime_bondPoint_atm2 = s2 #Determine bondpoint1 and bondPoint2 (the ones we will bond). See method #docstring for details. if five_prime_bondPoint_atm1 and three_prime_bondPoint_atm2: bondPoint1 = five_prime_bondPoint_atm1 bondPoint2 = three_prime_bondPoint_atm2 #Following will overwrite bondpoint1 and bondPoint2, if the condition is #True. Doesn't matter. See method docstring to know why. if three_prime_bondPoint_atm1 and five_prime_bondPoint_atm2: bondPoint1 = three_prime_bondPoint_atm1 bondPoint2 = five_prime_bondPoint_atm2 #Do the actual bonding if bondPoint1 and bondPoint2: bond_at_singlets(bondPoint1, bondPoint2, move = False) else: print_compact_stack("Bug: unable to bond atoms %s and %s: " % (atm1, atm2) ) def _determine_axisAtomsToRemove(self, resizeEndAxisAtom, baseatoms, numberOfBasePairsToRemove): """ Determine the axis atoms to be removed from the Dna while resizing a DnaStrand or segment. Returns a list @param resizeEndAxisAtom: The axis atom at the resize end. @type resizeEndAxisAtom: B{Atom} @param baseatoms: A list of all axis atoms of the dna strand or segment to be resized @type baseatoms: list @param numberOfBasePairsToRemove: Number of bases (if resizing strands) or number of base-pairs (it resizing DnaSegments) to be removed during the resize operation. this number is used to determine the axis atoms to remove (including the resizeEndAxisAtom) @type numberOfBasePairsToRemove: int @return : axis atoms to be removed during resize operation. The caller then uses this list to determine which strand base atoms need to be deleted. @rtype: list @see: self._remove_bases_from_dna() which calls this. """ atm = resizeEndAxisAtom resizeEnd_strand_neighbors = self._strand_neighbors_to_delete(atm) strand_neighbors_to_delete = resizeEnd_strand_neighbors axisAtomsToRemove = [] try: resizeEndAtom_baseindex = baseatoms.index(resizeEndAxisAtom) # note: this is an index in a list of baseatoms, which is not # necessary equal to the atom's "baseindex" (since that can be # negative for some atoms), but should be in the same order. # [bruce 080807 comment] except: print_compact_traceback("bug resize end axis atom not in " \ "segments baseatoms!: ") return if resizeEndAtom_baseindex == 0: axisAtomsToRemove = baseatoms[:numberOfBasePairsToRemove] elif resizeEndAtom_baseindex == len(baseatoms) - 1: axisAtomsToRemove = baseatoms[-numberOfBasePairsToRemove:] else: #The axis atom is not at either 'ends' of the DnaSegment. So, #check if is a single strand that is being resized. In that case, #the axis atom at the resize end may not be at the extreme ends. #see bug 2939 for an example. The following code fixes that bug. if len(resizeEnd_strand_neighbors) == 1: #Axis neighbors of the resize end axis atom (len 0 or 1 or 2) -- next_axis_atoms = resizeEndAxisAtom.axis_neighbors() #strand atom at the resize end resizeEndStrandAtom = resizeEnd_strand_neighbors[0] #Find out the next strand base atom bonded to the the resize #end strand atom. This will give us the connected axis neighbor #In the following figure, S1 is the resize end strand atom, #A1 is resize end axis atom. S2 is next_strand_atom and A2 #is next_axis_atom. # # ---o----o----o----S2----S1----> (strand being resized) # ---x----x----x----A2----A1----x----x----x----x (axis) #<---o----o----o----o ---- o----o----o----o----o (second strand) #Note that resize end strand atom will have only one strand base #atom connected to it. This code will never be reached if it has #more than 1 strand atoms connected! next_strand_atom = None #The axis neighbor of next_strand_atom next_axis_atom = None for bond_direction in (1, -1): next_strand_atom = resizeEndStrandAtom.strand_next_baseatom(bond_direction) if next_strand_atom: next_axis_atom = next_strand_atom.axis_neighbor() break if not next_axis_atom: print_compact_stack("bug: end axis atom not at "\ "either end of list and unable to" \ "determine axisAtomsToRemove") return axisAtomsToRemove if not next_axis_atom in resizeEndAxisAtom.axis_neighbors(): print_compact_stack( "bug:unable to determine axisAtomsToRemove"\ "%s not an axis neighbor of %s"%(next_axis_atom, resizeEndAxisAtom)) next_axis_atom_baseindex = baseatoms.index(next_axis_atom) if resizeEndAtom_baseindex < next_axis_atom_baseindex: startindex = resizeEndAtom_baseindex endindex = startindex + numberOfBasePairsToRemove axisAtomsToRemove = baseatoms[startindex:endindex] else: startindex = resizeEndAtom_baseindex - (numberOfBasePairsToRemove - 1) endindex = resizeEndAtom_baseindex + 1 axisAtomsToRemove = baseatoms[startindex:endindex] else: #Its not a strand resize operation and still the axis atom at resize #end is not at an extreme end. This indicates a bug. print_compact_stack("bug: end axis atom not at either end of list: ") #bruce 080807 added this assert len(axisAtomsToRemove) == min(numberOfBasePairsToRemove, len(baseatoms)) #bruce 080807 added this return axisAtomsToRemove def _remove_bases_from_dna(self, group, resizeEndAxisAtom, numberOfBasePairsToRemove): """ Remove the specified number of base pairs from the duplex. @param group: The DnaGroup which contains this duplex @type group: DnaGroup @param resizeEndAxisAtom: The end axis base atom at a DnaLadder end of the duplex. This end base atom is used as a starting base atom while determining which base atoms to remove. @type resizeEndAxisAtom: Atom @param numberOfBasePairsToRemove: The total number of base pairs to remove from the duplex. @type numberOfBasePairsToRemove: int @see: self._determine_axisAtomsToRemove() """ #Use whole_chain.get_all_baseatoms_in_order() and then remove the #requested number of bases from the resize end given by #numberOfBasePairsToRemove (including the resize end axis atom). #this fixes bug 2924 -- Ninad 2008-08-07 segment = resizeEndAxisAtom.getDnaSegment() if not segment: print_compact_stack("bug: can't resize dna segment: ") return whole_chain = segment.get_wholechain() if whole_chain is None: print_compact_stack("bug: can't resize dna segment: ") #bruce 080807 added this return baseatoms = whole_chain.get_all_baseatoms_in_order() if len(baseatoms) < 2: print_compact_stack("WARNING: resizing a dna segment with < 2 "\ "base atoms is not supported: ") return atomsScheduledForDeletionDict = {} axisAtomsToRemove = self._determine_axisAtomsToRemove( resizeEndAxisAtom, baseatoms, numberOfBasePairsToRemove) for atm in axisAtomsToRemove: strand_neighbors_to_delete = self._strand_neighbors_to_delete(atm) for a in strand_neighbors_to_delete: if not atomsScheduledForDeletionDict.has_key(id(a)): atomsScheduledForDeletionDict[id(a)] = a #Add the axis atom to the atoms scheduled for deletion only when #both the strand neighbors of this axis atom are scheduled for #deletion. But this is not true if its a sticky end i.e. the #axis atom has only one strand atom. To fix that problem #we also check (second condition) if all the strand neighbors #of an axis atom are scheduled for deletion... if so, ot also #adds that axis atom to the atom scheduled for deletion) #Axis atoms are explicitely deleted to fix part of memory #leak bug 2880 (and thus no longer depends on dna updater #to delete bare axis atoms .. which is good because there is a #debug pref that permits bare axis atoms for some other #uses -- Ninad 2008-05-15 if len(strand_neighbors_to_delete) == 2 or \ len(atm.strand_neighbors()) == len(strand_neighbors_to_delete): if not atomsScheduledForDeletionDict.has_key(id(atm)): atomsScheduledForDeletionDict[id(atm)] = atm else: print "unexpected: atom %r already in atomsScheduledForDeletionDict" % atm #bruce 080807 added this # REVIEW: if any atom can be added twice to that dict above without # this being a bug, then the has_key tests can simply be removed # (as an optimization). If adding it twice is a bug, then we should # print a warning when it happens, as I added in one case above # (but would be good in both cases). [bruce 080807 comment] #Now kill all the atoms. # [TODO: the following ought to be encapsulated in a helper method to # efficiently kill any set of atoms; similar code may exist in # several places. [bruce 080807 comment]] # #Before killing them, set a flag on each atom so that #Atom.kill knows not to create new bondpoints on its neighbors if they #will also be killed right now (it notices this by noticing that #a._f_will_kill has the same value on both atoms). Fixes a memory leak #(at least in some code where it's done). See bug 2880 for details. val = Atom_prekill_prep() for a in atomsScheduledForDeletionDict.itervalues(): a._f_will_kill = val # inlined a._f_prekill(val), for speed for atm in atomsScheduledForDeletionDict.values(): if atm: # this test is probably not needed [bruce 080807 comment] try: atm.kill() except: print_compact_traceback("bug in deleting atom while "\ "resizing the segment: ") atomsScheduledForDeletionDict.clear() #IMPORTANT TO RUN DNA UPDATER after deleting these atoms! Otherwise we #will have to wait for next event to finish before the dna updater runs. #There are things like resize handle positions that depend on the #axis end atoms of a dna segment. Those update methods may be called #before dna updater is run again, thereby spitting out errors. self.assy.update_parts() def _strand_neighbors_to_delete(self, axisAtom): """ Overridden in subclasses Returns a list of strand neighbors of the given axis atom to delete from the original dna being resized (and resizing will result in removing bases/ basepairs from the dna). This method determines whether both the strand neigbors of this axisAtom need to be deleted or is it just a single strand neighbor on a specific Dna ladder needs to be deleted. The latter is the case while resizing a single strand of a Dna. @see: self._remove_bases_from_dna() where this is called. @see: B_Dna_PAM3_Generator._strand_neighbors_to_delete() @see: B_Dna_PAM3_SingleStrand_Generator._strand_neighbors_to_delete() """ return () def make(self, group, numberOfBasePairs, basesPerTurn, duplexRise, endPoint1, endPoint2, position = V(0, 0, 0)): """ Makes a DNA duplex with the I{numberOfBase} base-pairs. The duplex is oriented with its central axis coincident to the line (endPoint1, endPoint1), with its origin at endPoint1. @param assy: The assembly (part). @type assy: L{assembly} @param group: The group node object containing the DNA. The caller is responsible for creating an empty group and passing it here. When finished, this group will contain the DNA model. @type group: L{Group} @param numberOfBasePairs: The number of base-pairs in the duplex. @type numberOfBasePairs: int @param basesPerTurn: The number of bases per helical turn. @type basesPerTurn: float @param duplexRise: The rise; the distance between adjacent bases. @type duplexRise: float @param endPoint1: The origin of the duplex. @param endPoint1: L{V} @param endPoint2: The second point that defines central axis of the duplex. @param endPoint2: L{V} @param position: The position in 3d model space at which to create the DNA strand. This should always be 0, 0, 0. @type position: position @see: self.fuseBasePairChunks() @see:self._insertBasesFromMMP() @see: self._regroup() @see: self._postProcess() @see: self._orient() @see: self._rotateTranslateXYZ() """ self.assy = group.assy assy = group.assy #Make sure to clear self.baseList each time self.make() is called self.baseList = [] self.setNumberOfBasePairs(numberOfBasePairs) self.setBaseRise(duplexRise) #See a note in DnaSegment_EditCommand._createStructure(). Should #the parentGroup object <group> be assigned properties such as #duplexRise, basesPerTurn in this method itself? to be decided #once dna data model is fully functional (and when this method is #revised) -- Ninad 2008-03-05 self.setBasesPerTurn(basesPerTurn) #End axis atom at end1. i.e. the first mouse click point from which #user started drawing the dna duplex (rubberband line). This is initially #set to None. When we start creating the duplex and read in the first #mmp file: MiddleBasePair.mmp, we assign the appropriate atom to this #variable. See self._determine_axis_and_strandA_endAtoms_at_end_1() self.axis_atom_end1 = None #The strand base atom of Strand-A, connected to the self.axis_atom_end1 #The vector between self.axis_atom_end1 and self.strandA_atom_end1 #is used to determine the final orientation of the created duplex. #that aligns this vector such that it is parallel to the screen. #see self._orient_to_position_first_strandA_base_in_axis_plane() for more details. self.strandA_atom_end1 = None #Create a duplex by inserting basepairs from the mmp file. self._create_raw_duplex(group, numberOfBasePairs, basesPerTurn, duplexRise, position = position) # Orient the duplex. self._orient(self.baseList, endPoint1, endPoint2) #do further adjustments so that first base of strandA always lies #in the screen parallel plane, which is passing through the #axis. self._orient_to_position_first_strandA_base_in_axis_plane(self.baseList, endPoint1, endPoint2) # Regroup subgroup into strand and chunk groups self._regroup(group) return #START -- Helper methods used in generating dna (see self.make())=========== def _create_raw_duplex(self, group, numberOfBasePairs, basesPerTurn, duplexRise, position = V(0, 0, 0)): """ Create a raw dna duplex in the specified group. This will be created along the Z axis. Later it will undergo more operations such as orientation change anc chunk regrouping. @return: A group object containing the 'raw dna duplex' @see: self.make() """ # Make the duplex. subgroup = group subgroup.open = False # Calculate the twist per base in radians. twistPerBase = (self.handedness * 2 * pi) / basesPerTurn theta = 0.0 z = 0.5 * duplexRise * (numberOfBasePairs - 1) # Create duplex. for i in range(numberOfBasePairs): basefile, zoffset, thetaOffset = self._strandAinfo(i) def tfm(v, theta = theta + thetaOffset, z1 = z + zoffset): return self._rotateTranslateXYZ(v, theta, z1) #Note that self.baseList gets updated in the the following method self._insertBaseFromMmp(basefile, subgroup, tfm, self.baseList, position = position) if i == 0: #The chunk self.baseList[0] should always contain the information #about the strand end and axis end atoms at end1 we are #interested in. This chunk is obtained by reading in the #first mmp file (at i =0) . #Note that we could have determined this after the for loop #as well. But now harm in doing it here. This is also safe #from any accidental modifications to the chunk after the for #loop. Note that 'self.baseList' gets populated in #sub 'def insertBasesFromMMP'.... Related TODO: The method #'def make' itself needs reafcatoring so that all submethods are #direct methods of class Dna. #@see self._determine_axis_and_strandA_endAtoms_at_end_1() for #more comments firstChunkInBaseList = self.baseList[0] #@ATTENTION: The strandA endatom at end1 is later modified #in self.orient_for_modify (if its a resize operation) #Its done to fix bug 2888 (for v1.1.0). #Perhaps computing this strand atom always be done at a later #stage. But I am unsure if this will cause any bugs. So not #changing the original implementation . #See B_Dna_PAM3_Generator.orient_for_modify() for details. #This NEEDS CLEANUP -- Ninad 2008-06-02 self._determine_axis_and_strandA_endAtoms_at_end_1(self.baseList[0]) theta -= twistPerBase z -= duplexRise # Fuse the base-pair chunks together into continuous strands. self.fuseBasePairChunks(self.baseList) try: self._postProcess(self.baseList) except: if env.debug(): print_compact_traceback( "debug: exception in %r._postProcess(self.baseList = %r) " \ "(reraising): " % (self, self.baseList,)) raise def _insertBaseFromMmp(self, filename, subgroup, tfm, baseList, position = V(0, 0, 0) ): """ Insert the atoms for a nucleic acid base from an MMP file into a single chunk. - If atomistic, the atoms for each base are in a separate chunk. - If PAM5, the pseudo atoms for each base-pair are together in a chunk. @param filename: The mmp filename containing the base (or base-pair). @type filename: str @param subgroup: The part group to add the atoms to. @type subgroup: L{Group} @param tfm: Transform applied to all new base atoms. @type tfm: V @param baseList: A list that maintains the bases inserted into the model Example self.baseList @param position: The origin in space of the DNA duplex, where the 3' end of strand A is 0, 0, 0. @type position: L{V} """ #@TODO: The argument baselist ACTUALLY MODIFIES self.baseList. Should we #directly use self.baseList instead? Only comments are added for #now. See also self.make()(the caller) try: ok, grouplist = readmmp(self.assy, filename, isInsert = True) except IOError: raise PluginBug("Cannot read file: " + filename) if not grouplist: raise PluginBug("No atoms in DNA base? " + filename) viewdata, mainpart, shelf = grouplist for member in mainpart.members: # 'member' is a chunk containing a full set of # base-pair pseudo atoms. for atm in member.atoms.values(): atm._posn = tfm(atm._posn) + position member.name = "BasePairChunk" subgroup.addchild(member) #Append the 'member' to the baseList. Note that this actually #modifies self.baseList. Should self.baseList be directly used here? baseList.append(member) # Clean up. del viewdata shelf.kill() def _rotateTranslateXYZ(self, inXYZ, theta, z): """ Returns the new XYZ coordinate rotated by I{theta} and translated by I{z}. @param inXYZ: The original XYZ coordinate. @type inXYZ: V @param theta: The base twist angle. @type theta: float @param z: The base rise. @type z: float @return: The new XYZ coordinate. @rtype: V """ c, s = cos(theta), sin(theta) x = c * inXYZ[0] + s * inXYZ[1] y = -s * inXYZ[0] + c * inXYZ[1] return V(x, y, inXYZ[2] + z) def fuseBasePairChunks(self, baseList, fuseTolerance = 1.5): """ Fuse the base-pair chunks together into continuous strands. @param baseList: The list of bases inserted in the model. See self.make (the caller) for an example. @see: self.make() @NOTE: self.assy is determined in self.make() so this method must be called from that method only. """ if self.assy is None: print_compact_stack("bug: self.assy not defined. Unable to fuse bases: ") return # Fuse the base-pair chunks together into continuous strands. fcb = fusechunksBase() fcb.tol = fuseTolerance for i in range(len(baseList) - 1): #Note that this is actually self.baseList that we are using. #Example see self.make() which calls this method. tol_string = fcb.find_bondable_pairs([baseList[i]], [baseList[i + 1]], ignore_chunk_picked_state = True ) fcb.make_bonds(self.assy) def _postProcess(self, baseList): return #END Helper methods used in dna generation (see self.make())================ def _baseFileName(self, basename): """ Returns the full pathname to the mmp file containing the atoms of a nucleic acid base (or base-pair). Example: If I{basename} is "MidBasePair" and this is a PAM5 model of B-DNA, this returns: - "C:$HOME\cad\plugins\DNA\B-DNA\PAM5-bases\MidBasePair.mmp" @param basename: The basename of the mmp file without the extention (i.e. "adenine", "MidBasePair", etc.). @type basename: str @return: The full pathname to the mmp file. @rtype: str """ form = self.form # A-DNA, B-DNA or Z-DNA model = self.model + '-bases' # PAM3 or PAM5 return os.path.join(basepath, form, model, '%s.mmp' % basename) def _orient(self, baseList, pt1, pt2): """ Orients the DNA duplex I{dnaGroup} based on two points. I{pt1} is the first endpoint (origin) of the duplex. The vector I{pt1}, I{pt2} defines the direction and central axis of the duplex. @param pt1: The starting endpoint (origin) of the DNA duplex. @type pt1: L{V} @param pt2: The second point of a vector defining the direction and central axis of the duplex. @type pt2: L{V} """ a = V(0.0, 0.0, -1.0) # <a> is the unit vector pointing down the center axis of the default # DNA structure which is aligned along the Z axis. bLine = pt2 - pt1 bLength = vlen(bLine) b = bLine/bLength # <b> is the unit vector parallel to the line (i.e. pt1, pt2). axis = cross(a, b) # <axis> is the axis of rotation. theta = angleBetween(a, b) # <theta> is the angle (in degress) to rotate about <axis>. scalar = self.getBaseRise() * (self.getNumberOfBasePairs() - 1) * 0.5 rawOffset = b * scalar if 0: # Debugging code. print "~~~~~~~~~~~~~~" print "uVector a = ", a print "uVector b = ", b print "cross(a,b) =", axis print "theta =", theta print "baserise =", self.getBaseRise() print "# of bases =", self.getNumberOfBasePairs() print "scalar =", scalar print "rawOffset =", rawOffset if theta == 0.0 or theta == 180.0: axis = V(0, 1, 0) # print "Now cross(a,b) =", axis rot = (pi / 180.0) * theta # Convert to radians qrot = Q(axis, rot) # Quat for rotation delta. # Move and rotate the base chunks into final orientation. ##for m in dnaGroup.members: for m in baseList: if isinstance(m, self.assy.Chunk): m.move(qrot.rot(m.center) - m.center + rawOffset + pt1) m.rot(qrot) def _determine_axis_and_strandA_endAtoms_at_end_1(self, chunk): """ Overridden in subclasses. Default implementation does nothing. @param chunk: The method itereates over chunk atoms to determine strand and axis end atoms at end 1. @see: B_DNA_PAM3._determine_axis_and_strandA_endAtoms_at_end_1() for documentation and implementation. """ pass def _orient_for_modify(self, baseList, end1, end2): pass def _orient_to_position_first_strandA_base_in_axis_plane(self, baseList, end1, end2): """ Overridden in subclasses. Default implementation does nothing. The self._orient method orients the DNA duplex parallel to the screen (lengthwise) but it doesn't ensure align the vector through the strand end atom on StrandA and the corresponding axis end atom (at end1) , parallel to the screen. This function does that ( it has some rare bugs which trigger where it doesn't do its job but overall works okay ) What it does: After self._orient() is done orienting, it finds a Quat that rotates between the 'desired vector' between strand and axis ends at end1(aligned to the screen) and the actual vector based on the current positions of these atoms. Using this quat we rotate all the chunks (as a unit) around a common center. @BUG: The last part 'rotating as a unit' uses a readymade method in ops_motion.py -- 'rotateSpecifiedMovables' . This method itself may have some bugs because the axis of the dna duplex is slightly offset to the original axis. @see: self._determine_axis_and_strandA_endAtoms_at_end_1() @see: self.make() @see: B_DNA_PAM3._orient_to_position_first_strandA_base_in_axis_plane """ pass def _regroup(self, dnaGroup): """ Regroups I{dnaGroup} into group containing three chunks: I{StrandA}, I{StrandB} and I{Axis} of the DNA duplex. @param dnaGroup: The DNA group which contains the base-pair chunks of the duplex. @type dnaGroup: L{Group} @return: The new DNA group that contains the three chunks I{StrandA}, I{StrandB} and I{Axis}. @rtype: L{Group} """ #Get the lists of atoms (two lists for two strands and one for the axis #for creating new chunks _strandA_list, _strandB_list, _axis_list = \ self._create_atomLists_for_regrouping(dnaGroup) # Create strand and axis chunks from atom lists and add # them to the dnaGroup. # [bruce 080111 add conditions to prevent bugs in PAM5 case # which is not yet supported in the above code. It would be # easy to support it if we added dnaBaseName assignments # into the generator mmp files and generalized the above # symbol names, and added a 2nd pass for Pl atoms. # update, bruce 080311: it looks like something related to # this has been done without this comment being updated.] if _strandA_list: strandAChunk = self._makeChunkFromAtomList( _strandA_list, name = gensym("Strand", self.assy), group = dnaGroup, color = env.prefs[dnaDefaultStrand1Color_prefs_key]) if _strandB_list: strandBChunk = self._makeChunkFromAtomList( _strandB_list, name = gensym("Strand", self.assy), group = dnaGroup, color = env.prefs[dnaDefaultStrand2Color_prefs_key]) if _axis_list: axisChunk = self._makeChunkFromAtomList( _axis_list, name = "Axis", group = dnaGroup, color = env.prefs[dnaDefaultSegmentColor_prefs_key]) return def _makeChunkFromAtomList(self, atomList, **options): #bruce 080326 split this out, revised it for PAM3+5 (partway) chunk = self.assy.makeChunkFromAtomList( atomList, **options) ### todo: in some cases, set chunk.display_as_pam = MODEL_PAM5 # initial stub: always do that (when making PAM5 dna), # but only if edit pref would otherwise immediately convert it to PAM3. #update, bruce 080401: always do it, regardless of that edit pref. #update, bruce 080523: never do it, until the bug 2842 dust completely # settles. See also a comment added in rev 12846. This is #2 of 2 changes # (in the same commit) which eliminates all ways of setting this attribute, # thus fixing bug 2842 well enough for v1.1. ## if self.model == "PAM5": ## and pref_dna_updater_convert_to_PAM3plus5(): ## if debug_flags.atom_debug: ## print "debug fyi: %r is setting .display_as_pam = MODEL_PAM5 " \ ## "on %r" % (self, chunk) ## chunk.display_as_pam = MODEL_PAM5 return chunk def getBaseRise( self ): """ Get the base rise (spacing) between base-pairs. """ return float( self.baseRise ) def setBaseRise( self, inBaseRise ): """ Set the base rise (spacing) between base-pairs. @param inBaseRise: The base rise in Angstroms. @type inBaseRise: float """ self.baseRise = inBaseRise def getNumberOfBasePairs( self ): """ Get the number of base-pairs in this duplex. """ return self.numberOfBasePairs def setNumberOfBasePairs( self, inNumberOfBasePairs ): """ Set the base rise (spacing) between base-pairs. @param inNumberOfBasePairs: The number of base-pairs. @type inNumberOfBasePairs: int """ self.numberOfBasePairs = inNumberOfBasePairs def setBasesPerTurn(self, basesPerTurn): """ Sets the number of base pairs per turn @param basesPerTurn: Number of bases per turn @type basesPerTurn: int """ self.basesPerTurn = basesPerTurn def getBasesPerTurn(self): """ returns the number of bases per turn in the duplex """ return self.basesPerTurn pass
NanoCAD-master
cad/src/dna/generators/Dna_Generator.py
NanoCAD-master
cad/src/dna/temporary_commands/__init__.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. @version: $Id$ @license: GPL TODO: - User Preferences for different rubberband line display styles """ from utilities.constants import black, white from utilities.prefs_constants import dnaDefaultStrand1Color_prefs_key from utilities.prefs_constants import dnaDefaultStrand2Color_prefs_key import foundation.env as env from graphics.drawing.drawDnaLadder import drawDnaLadder from graphics.drawing.drawDnaRibbons import drawDnaRibbons from temporary_commands.LineMode.Line_Command import Line_Command from temporary_commands.LineMode.Line_GraphicsMode import Line_GraphicsMode # == GraphicsMode part _superclass_for_GM = Line_GraphicsMode class DnaLine_GM( Line_GraphicsMode ): """ Custom GraphicsMode for use as a component of DnaLineMode. @see: L{DnaLineMode} for more comments. @see: InsertDna_EditCommand where this is used as a GraphicsMode class. The default command part in this file is a Default class implementation of self.command (see class DnaLineMode) """ # The following valuse are used in drawing the 'sphere' that represent the #first endpoint of the line. See Line_GraphicsMode.Draw_other for details. endPoint1_sphereColor = white endPoint1_sphereOpacity = 1.0 text = '' def __init__(self, command): """ """ _superclass_for_GM.__init__(self, command) def leftUp(self, event): """ Left up method """ if self.isSpecifyPlaneToolActive(): _superclass_for_GM.leftUp(self, event) return if self.command.mouseClickLimit is None: if len(self.command.mouseClickPoints) == 2: self.endPoint2 = None self.command.createStructure() self.glpane.gl_update() return def snapLineEndPoint(self): """ Snap the line to the specified constraints. To be refactored and expanded. @return: The new endPoint2 i.e. the moving endpoint of the rubberband line . This value may be same as previous or snapped so that it lies on a specified vector (if one exists) @rtype: B{A} """ if self.command.callbackForSnapEnabled() == 1: endPoint2 = _superclass_for_GM.snapLineEndPoint(self) else: endPoint2 = self.endPoint2 return endPoint2 def Draw_other(self): """ Draw the DNA rubberband line (a ladder representation) """ #The rubberband line display needs to be a user preference. #Example: There could be 3 radio buttons in the duplex PM that allows #you to draw the rubberband line as a simple line, a line with points #that indicate duplexrise, a dna ladder with arrow heads. Drawing it as #a ladder with arrow heads for the beams is the current implementation # -Ninad 2007-10-30 #@see: Line_GraphicsMode class definition about this flag. Basically we suppress #cursor text drawing in the superclass and draw later in this method #after everyting is drawn. # [update, bruce 090310. This could use refactoring. Not urgent.] self._ok_to_render_cursor_text = False _superclass_for_GM.Draw_other(self) self._ok_to_render_cursor_text = True #This fixes NFR bug 2803 #Don't draw the Dna rubberband line if the cursor is over the confirmation #corner. But make sure to call superclass.Draw_other method before doing this #check because we need to draw the rest of the model in the graphics #mode!. @see: Line_GraphicsMode.Draw_other # [update, bruce 090310: that superclass call no longer draws the model, # but might still be needed for other reasons. Also, how this is implemented # is questionable; see longer review comment in the superclass.] handler = self.o.mouse_event_handler if handler is not None and handler is self._ccinstance: return if self.endPoint2 is not None and \ self.endPoint1 is not None: #Draw the ladder. #Convention: # The red band(beam) of the # ladder is always the 'leading edge' of the ladder. i.e. the red # band arrow head is always at the moving end of the mouse #(endpoint2). # A General Note/ FYI to keep in mind: # Consider a double stranded DNA and focus on the 'twin peaks' #(say, two consecutive helices in the middle of the dna duplex) # From the "mountain" with twin peaks that is the minor groove, # the DNA flows downhill 5' to 3' # Or in other words, # - For the 'mountain peak' on the right , # the 5' to 3' flows downhill, from left to right. # - For the 'mountain peak' on the left, # the 3' to 5' flows downhill, from right to left # # Thus, the red beam of the ladder, can either become the # 'left mountain' or the 'right mountain' depending on the # orientation while drawing the ladder if self.command.callback_rubberbandLineDisplay() == 'Ladder': # Note: there needs to be a radio button to switch on the # rubberband ladder display for a dna line. At the moment it is # disabled and is superseded by the ribbons ruberband display. drawDnaLadder(self.endPoint1, self.endPoint2, self.command.duplexRise, self.glpane.scale, self.glpane.lineOfSight, beamThickness = 4.0, beam1Color = env.prefs[dnaDefaultStrand1Color_prefs_key], beam2Color = env.prefs[dnaDefaultStrand2Color_prefs_key], ) elif self.command.callback_rubberbandLineDisplay() == 'Ribbons': #Default dna rubberband line display style drawDnaRibbons(self.glpane, self.endPoint1, self.endPoint2, self.command.basesPerTurn, self.command.duplexRise, self.glpane.scale, self.glpane.lineOfSight, self.glpane.displayMode, ribbonThickness = 4.0, ribbon1Color = env.prefs[dnaDefaultStrand1Color_prefs_key], ribbon2Color = env.prefs[dnaDefaultStrand2Color_prefs_key], ) else: pass self._drawCursorText() pass return pass # end of class DnaLine_GM # == Command part class DnaLineMode(Line_Command): # not used as of 080111, see docstring """ [no longer used as of 080111, see details below] Encapsulates the Line_Command functionality. @see: L{Line_Command} @see: InsertDna_EditCommand.getCursorText NOTE: [2008-01-11] The default DnaLineMode (command) part is not used as of 2008-01-11 Instead, the interested commands use its GraphicsMode class. However, it's still possible to use and implement the default command part. (The old implementation of generating Dna using endpoints of a line used this default command class (DnaLineMode). so the method in this class such as self.createStructure does nothing . @see: InsertDna_EditCommand where the GraphicsMode class of this command is used """ # class constants commandName = 'DNA_LINE_MODE' featurename = "DNA Line Mode" # (This featurename is sometimes user-visible, # but is probably not useful. See comments in Line_Command # for more info and how to fix. [bruce 071227]) from utilities.constants import CL_UNUSED command_level = CL_UNUSED GraphicsMode_class = DnaLine_GM def setParams(self, params): assert len(params) == 5 self.mouseClickLimit, \ self.duplexRise, \ self.callbackMethodForCursorTextString, \ self.callbackForSnapEnabled, \ self.callback_rubberbandLineDisplay = params def createStructure(self): """ Does nothing. @see: DnaLineMode_GM.leftUp @see: comment at the beginning of the class """ pass pass # end
NanoCAD-master
cad/src/dna/temporary_commands/DnaLineMode.py
# Copyright 2005-2009 Nanorex, Inc. See LICENSE file for details. """ Rotate mode functionality. @author: Mark Sims @version: $Id$ @copyright: 2005-2009 Nanorex, Inc. See LICENSE file for details. @license: GPL piotr 080808: added "auto-rotation" feature. """ from temporary_commands.TemporaryCommand import TemporaryCommand_Overdrawing from PyQt4.Qt import Qt, QTimer, SIGNAL ## from utilities.debug import set_enabled_for_profile_single_call ## clicked = False # == GraphicsMode part _superclass = TemporaryCommand_Overdrawing.GraphicsMode_class class RotateMode_GM( TemporaryCommand_Overdrawing.GraphicsMode_class ): """ Custom GraphicsMode for use as a component of RotateMode. """ def __init__(self, glpane): TemporaryCommand_Overdrawing.GraphicsMode_class.__init__(self, glpane) self.auto_rotate = False # set to True when user presses "A" key while self.animationTimer = None # time used to animate view self.last_quat = None # last quaternion to be used for incremental rotation def leftDown(self, event): ## global clicked ## clicked = True self.glpane.SaveMouse(event) self.glpane.trackball.start(self.glpane.MousePos[0], self.glpane.MousePos[1]) # piotr 080807: The most recent quaternion to be used for "auto-rotate" # animation, initially set to None, so the animation stops when # user pushes down mouse button. self.last_quat = None self.picking = False return def leftDrag(self, event): ## global clicked ## if clicked: ## set_enabled_for_profile_single_call(True) ## clicked = False self.glpane.SaveMouse(event) q = self.glpane.trackball.update(self.glpane.MousePos[0], self.glpane.MousePos[1]) self.glpane.quat += q # piotr 080807: Remember the most recent quaternion to be used # in 'auto_rotate' mode. Do it only if 'auto_rotate' class attribute # is True, i.e. when user pressed an "A" key while dragging the mouse. if self.auto_rotate: self.last_quat = q self.glpane.gl_update() self.picking = False return def leftUp(self, event): if self.last_quat: # Create and enable animation timer. if self.animationTimer is None: self.animationTimer = QTimer(self.glpane) self.win.connect(self.animationTimer, SIGNAL('timeout()'), self._animationTimerTimeout) self.animationTimer.start(20) # use 50 fps for smooth animation else: # Stop animation if mouse was not dragged. if self.animationTimer: self.animationTimer.stop() def _animationTimerTimeout(self): if self.last_quat: self.glpane.quat += self.last_quat self.glpane.gl_update() def update_cursor_for_no_MB(self): # Fixes bug 1638. Mark 3/12/2006 """ Update the cursor for 'Rotate' mode. """ self.glpane.setCursor(self.win.RotateViewCursor) return def keyPress(self, key): if key == Qt.Key_A: self.auto_rotate = True _superclass.keyPress(self, key) return def keyRelease(self, key): if key == Qt.Key_A: self.auto_rotate = False _superclass.keyRelease(self, key) return pass # == Command part class RotateMode(TemporaryCommand_Overdrawing): # TODO: rename to RotateTool or RotateCommand or TemporaryCommand_Rotate or ... """ Encapsulates the Rotate Tool functionality. """ # class constants commandName = 'ROTATE' featurename = "Rotate Tool" from utilities.constants import CL_VIEW_CHANGE command_level = CL_VIEW_CHANGE GraphicsMode_class = RotateMode_GM def command_will_exit(self): # Disable auto-rotation. self.graphicsMode.last_quat = False super(RotateMode, self).command_will_exit() def command_enter_misc_actions(self): """ See superclass method for documentation """ self.win.rotateToolAction.setChecked(True) def command_exit_misc_actions(self): """ See superclass method for documentation """ self.win.rotateToolAction.setChecked(False)
NanoCAD-master
cad/src/temporary_commands/RotateMode.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ Zoom to Area functionality. @author: Mark Sims @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @license: GPL History: Mark 2008-01-31: Renamed from ZoomMode to ZoomToAreaMode.py """ from Numeric import dot from OpenGL.GL import GL_DEPTH_TEST from OpenGL.GL import glDisable from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glColor3d from OpenGL.GL import GL_COLOR_LOGIC_OP from OpenGL.GL import glEnable from OpenGL.GL import GL_XOR from OpenGL.GL import glLogicOp from OpenGL.GL import glFlush from OpenGL.GL import GL_DEPTH_COMPONENT from OpenGL.GL import glReadPixelsf from OpenGL.GLU import gluUnProject from geometry.VQT import V, A from graphics.drawing.drawers import drawrectangle from utilities.constants import GL_FAR_Z from temporary_commands.TemporaryCommand import TemporaryCommand_Overdrawing # == the GraphicsMode part class ZoomToAreaMode_GM( TemporaryCommand_Overdrawing.GraphicsMode_class ): """ Custom GraphicsMode for use as a component of ZoomToAreaMode. """ def leftDown(self, event): """ Compute the rubber band window starting point, which lies on the near clipping plane, projecting into the same point that current cursor points at on the screen plane. """ self.pWxy = (event.pos().x(), self.glpane.height - event.pos().y()) p1 = A(gluUnProject(self.pWxy[0], self.pWxy[1], 0.005)) self.pStart = p1 self.pPrev = p1 self.firstDraw = True self.command.glStatesChanged = True # this warns our exit code to undo the following OpenGL state changes: self.glpane.redrawGL = False glDisable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) rbwcolor = self.command.rbwcolor glColor3d(rbwcolor[0], rbwcolor[1], rbwcolor[2]) glEnable(GL_COLOR_LOGIC_OP) glLogicOp(GL_XOR) return def leftDrag(self, event): """ Compute the changing rubber band window ending point. Erase the previous window, draw the new window. """ # bugs 1190, 1818 wware 4/05/2006 - sometimes Qt neglects to call leftDown # before this if not hasattr(self, "pWxy") or not hasattr(self, "firstDraw"): return cWxy = (event.pos().x(), self.glpane.height - event.pos().y()) rbwcolor = self.command.rbwcolor if not self.firstDraw: #Erase the previous rubberband window drawrectangle(self.pStart, self.pPrev, self.glpane.up, self.glpane.right, rbwcolor) self.firstDraw = False self.pPrev = A(gluUnProject(cWxy[0], cWxy[1], 0.005)) # draw the new rubberband window drawrectangle(self.pStart, self.pPrev, self.glpane.up, self.glpane.right, rbwcolor) glFlush() self.glpane.swapBuffers() # Update display # Based on a suggestion in bug 2961, I added this second call to # swapBuffers(). It definitely helps, but the rectangle disappears # once the zoom cursor stops moving. I suspect this is due to # a gl_update() elsewhere. I'll ask Bruce about his thoughts on # this. --Mark 2008-12-22. self.glpane.swapBuffers() return def leftUp(self, event): """ Erase the final rubber band window and do zoom if user indeed draws a rubber band window. """ # bugs 1190, 1818 wware 4/05/2006 - sometimes Qt neglects to call # leftDown before this if not hasattr(self, "pWxy") or not hasattr(self, "firstDraw"): return cWxy = (event.pos().x(), self.glpane.height - event.pos().y()) zoomX = (abs(cWxy[0] - self.pWxy[0]) + 0.0) / (self.glpane.width + 0.0) zoomY = (abs(cWxy[1] - self.pWxy[1]) + 0.0) / (self.glpane.height + 0.0) # The rubber band window size can be larger than that of glpane. # Limit the zoomFactor to 1.0 zoomFactor = min(max(zoomX, zoomY), 1.0) # Huaicai: when rubber band window is too small, # like a double click, a single line rubber band, skip zoom DELTA = 1.0E-5 if self.pWxy[0] == cWxy[0] or self.pWxy[1] == cWxy[1] \ or zoomFactor < DELTA: self.command.command_Done() return # Erase the last rubber-band window rbwcolor = self.command.rbwcolor drawrectangle(self.pStart, self.pPrev, self.glpane.up, self.glpane.right, rbwcolor) glFlush() self.glpane.swapBuffers() winCenterX = (cWxy[0] + self.pWxy[0]) / 2.0 winCenterY = (cWxy[1] + self.pWxy[1]) / 2.0 winCenterZ = \ glReadPixelsf(int(winCenterX), int(winCenterY), 1, 1, GL_DEPTH_COMPONENT) assert winCenterZ[0][0] >= 0.0 and winCenterZ[0][0] <= 1.0 if winCenterZ[0][0] >= GL_FAR_Z: # window center touches nothing p1 = A(gluUnProject(winCenterX, winCenterY, 0.005)) p2 = A(gluUnProject(winCenterX, winCenterY, 1.0)) los = self.glpane.lineOfSight k = dot(los, -self.glpane.pov - p1) / dot(los, p2 - p1) zoomCenter = p1 + k*(p2-p1) else: zoomCenter = \ A(gluUnProject(winCenterX, winCenterY, winCenterZ[0][0])) self.glpane.pov = V(-zoomCenter[0], -zoomCenter[1], -zoomCenter[2]) # The following are 2 ways to do the zoom, the first one # changes view angles, the 2nd one change viewing distance # The advantage for the 1st one is model will not be clipped by # near or back clipping planes, and the rubber band can be # always shown. The disadvantage: when the view field is too # small, a selection window may be actually act as a single pick. # rubber band window will not look as rectangular any more. #zf = self.glpane.getZoomFactor() # [note: method does not exist] #zoomFactor = pow(zoomFactor, 0.25) #zoomFactor *= zf #self.glpane.setZoomFactor(zoomFactor) # [note: method does not exist] # Change viewing distance to do zoom. This works better with # mouse wheel, since both are changing viewing distance, and # it's not too bad of model being clipped, since the near/far clip # plane change as scale too. self.glpane.scale *= zoomFactor self.command.command_Done() return def update_cursor_for_no_MB(self): # Fixes bug 1638. Mark 3/12/2006. """ Update the cursor for 'Zoom' mode. """ self.glpane.setCursor(self.win.ZoomCursor) def _restore_patches_by_GraphicsMode(self): """ This is run when we exit this command for any reason. """ # Note: this is no longer part of the GraphicsMode API # but we retain it as an essentially private method and call it from # self.command.command_will_exit in that case. [bruce 080829 comment] #(comment slightly updated on 2008-09-26 : removed reference to #the 'new command api' because it is now the default API we use # -- Ninad) # [bruce 080929 made this private] # If OpenGL states changed during this mode, we need to restore # them before exit. Currently, only leftDown() will change that. # [bruce 071011/071012 change: do this in # _restore_patches_by_GraphicsMode, not in Done] if self.command.glStatesChanged: self.glpane.redrawGL = True glDisable(GL_COLOR_LOGIC_OP) glEnable(GL_LIGHTING) glEnable(GL_DEPTH_TEST) return pass # == the Command part class ZoomToAreaMode(TemporaryCommand_Overdrawing): """ Encapsulates the Zoom Tool functionality. """ # TODO: rename to ZoomTool or ZoomCommand or TemporaryCommand_Zoom or ... # class constants commandName = 'ZOOMTOAREA' featurename = "Zoom to Area Tool" from utilities.constants import CL_VIEW_CHANGE command_level = CL_VIEW_CHANGE GraphicsMode_class = ZoomToAreaMode_GM def command_entered(self): super(ZoomToAreaMode, self).command_entered() bg = self.glpane.backgroundColor # rubber window shows as white color normally, but when the # background becomes bright, we'll set it as black. brightness = bg[0] + bg[1] + bg[2] if brightness > 1.5: self.rbwcolor = bg # note: accessed as self.command.rbwcolor in our GraphicsMode part else: # REVIEW: should the following color be converted to tuple(), # in case it's black and the Numeric.array version # would fool some code due to being boolean false? # [bruce 080829 question] self.rbwcolor = A((1.0, 1.0, 1.0)) - A(bg) self.glStatesChanged = False # note: accessed as self.command.glStatesChanged in our GraphicsMode part return def command_enter_misc_actions(self): super(ZoomToAreaMode, self).command_enter_misc_actions() self.win.zoomToAreaAction.setChecked(1) # toggle on the Zoom Tool icon def command_exit_misc_actions(self): self.win.zoomToAreaAction.setChecked(0) # toggle off the Zoom Tool icon super(ZoomToAreaMode, self).command_exit_misc_actions() def command_will_exit(self): self.graphicsMode._restore_patches_by_GraphicsMode() super(ZoomToAreaMode, self).command_will_exit() return
NanoCAD-master
cad/src/temporary_commands/ZoomToAreaMode.py
NanoCAD-master
cad/src/temporary_commands/__init__.py
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. """ Pan mode functionality. @author: Mark Sims @version: $Id$ @copyright: 2005-2007 Nanorex, Inc. See LICENSE file for details. @license: GPL """ from temporary_commands.TemporaryCommand import TemporaryCommand_Overdrawing # == GraphicsMode part class PanMode_GM( TemporaryCommand_Overdrawing.GraphicsMode_class ): """ Custom GraphicsMode for use as a component of PanMode. """ def leftDown(self, event): """ Event handler for LMB press event. """ # Setup pan operation farQ_junk, self.movingPoint = self.dragstart_using_GL_DEPTH( event) return def leftDrag(self, event): """ Event handler for LMB drag event. """ point = self.dragto( self.movingPoint, event) self.glpane.pov += point - self.movingPoint self.glpane.gl_update() return def update_cursor_for_no_MB(self): # Fixes bug 1638. Mark 3/12/2006. """ Update the cursor for 'Pan' mode. """ self.glpane.setCursor(self.win.PanViewCursor) pass # == Command part class PanMode(TemporaryCommand_Overdrawing): # TODO: rename to PanTool or PanCommand or TemporaryCommand_Pan or ... """ Encapsulates the Pan tool functionality. """ # class constants commandName = 'PAN' featurename = "Pan Tool" from utilities.constants import CL_VIEW_CHANGE command_level = CL_VIEW_CHANGE GraphicsMode_class = PanMode_GM def command_enter_misc_actions(self): """ See superclass method for documentation """ self.win.panToolAction.setChecked(True) def command_exit_misc_actions(self): """ See superclass method for documentation """ self.win.panToolAction.setChecked(False)
NanoCAD-master
cad/src/temporary_commands/PanMode.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: TODO: 2008-04-20 - Created a support a NFR to rotate about a point just before FNANO 2008 conference. This may be revised further. -- Need documentation """ from Numeric import dot import math # for pi from utilities.prefs_constants import atomHighlightColor_prefs_key from utilities.constants import black from utilities.prefs_constants import DarkBackgroundContrastColor_prefs_key from utilities.debug import print_compact_stack, print_compact_traceback from geometry.VQT import cross, norm, Q import foundation.env as env from graphics.drawing.CS_draw_primitives import drawline from model.chem import Atom # for isinstance check as of 2008-04-17 from temporary_commands.LineMode.Line_Command import Line_Command from temporary_commands.LineMode.Line_GraphicsMode import Line_GraphicsMode # == _superclass_for_GM = Line_GraphicsMode class RotateAboutPoint_GraphicsMode(Line_GraphicsMode): pivotPoint = None def Enter_GraphicsMode(self): #TODO: use this more widely, than calling grapicsMode.resetVariables #in command.restore_GUI. Need changes in superclasses etc #-- Ninad 2008-04-17 self.resetVariables() # For safety def Draw_other(self): """ """ _superclass_for_GM.Draw_other(self) if len(self.command.mouseClickPoints) >= 2: #Draw reference vector. drawline(env.prefs[DarkBackgroundContrastColor_prefs_key], self.command.mouseClickPoints[0], self.command.mouseClickPoints[1], width = 4, dashEnabled = True) def resetVariables(self): _superclass_for_GM.resetVariables(self) self.pivotPoint = None def _determine_pivotPoint(self, event): """ Determine the pivot point about which to rotate the selection """ self.pivotPoint = None selobj = self.glpane.selobj if isinstance(selobj, Atom): self.pivotPoint = selobj.posn() else: farQ_junk, self.pivotPoint = self.dragstart_using_GL_DEPTH( event) def leftDown(self, event): """ Event handler for LMB press event. """ #The endPoint1 and self.endPoint2 are the mouse points at the 'water' #surface. Soon, support will be added so that these are actually points #on a user specified reference plane. Also, once any temporary mode # begins supporting highlighting, we can also add feature to use # coordinates of a highlighted object (e.g. atom center) as endpoints # of the line selobj = self.glpane.selobj if len(self.command.mouseClickPoints) == 0: self._determine_pivotPoint(event) self.endPoint1 = self.pivotPoint if isinstance(selobj, Atom): mouseClickPoint = selobj.posn() else: if self.pivotPoint is not None: planeAxis = self.glpane.lineOfSight planePoint = self.pivotPoint mouseClickPoint = self.dragstart_using_plane_depth( event, planeAxis = planeAxis, planePoint = planePoint) else: farQ_junk, mouseClickPoint = self.dragstart_using_GL_DEPTH( event) if self._snapOn and self.endPoint2 is not None: # This fixes a bug. Example: Suppose the dna line is snapped to a # constraint during the bare motion and the second point is clicked # when this happens, the second clicked point is the new #'self.endPoint1' which needs to be snapped like we did for # self.endPoint2 in the bareMotion. Setting self._snapOn to False # ensures that the cursor is set to the simple Pencil cursor after # the click -- Ninad 2007-12-04 mouseClickPoint = self.snapLineEndPoint() self._snapOn = False self.command.mouseClickPoints.append(mouseClickPoint) return def leftUp(self, event): """ Event handler for Left Mouse button left-up event @see: Line_Command._f_results_for_caller_and_prepare_for_new_input() """ if len(self.command.mouseClickPoints) == 3: self.endPoint2 = None self.command.rotateAboutPoint() try: self.command._f_results_for_caller_and_prepare_for_new_input() except AttributeError: print_compact_traceback( "bug: command %s has no attr"\ "'_f_results_for_caller_and_prepare_for_new_input'.") self.command.mouseClickPoints = [] self.resetVariables() self.glpane.gl_update() return assert len(self.command.mouseClickPoints) <= self.command.mouseClickLimit if len(self.command.mouseClickPoints) == self.command.mouseClickLimit: self.endPoint2 = None self._snapOn = False self._standardAxisVectorForDrawingSnapReference = None self.glpane.gl_update() self.command.rotateAboutPoint() #Exit this GM's command (i.e. the command 'RotateAboutPoint') self.command.command_Done() return def _getCursorText_length(self, vec): """ Overrides superclass method. @see: self._drawCursorText() for details. """ #Based on Mark's email (as of 2008-12-08) , the rotate about point don't #need length in the cursor text. So just return an empty string return '' def _getCursorText_angle(self, vec): """ Subclasses may override this method. @see: self._drawCursorText() for details. """ thetaString = '' if len(self.command.mouseClickPoints) < 2: theta = self.glpane.get_angle_made_with_screen_right(vec) thetaString = "%5.2f deg" % (theta,) else: ref_vector = norm(self.command.mouseClickPoints[1] - self.pivotPoint) quat = Q(vec, ref_vector) theta = quat.angle * 180.0 / math.pi thetaString = "%5.2f deg" % (theta,) return thetaString def _getAtomHighlightColor(self, selobj): return env.prefs[atomHighlightColor_prefs_key] def update_cursor_for_no_MB(self): """ Update the cursor for this mode. """ if self._snapOn: if self._snapType == 'HORIZONTAL': self.glpane.setCursor(self.win.rotateAboutPointHorizontalSnapCursor) elif self._snapType == 'VERTICAL': self.glpane.setCursor(self.win.rotateAboutPointVerticalSnapCursor) else: self.glpane.setCursor(self.win.rotateAboutPointCursor) pass # end of class RotateAboutPoint_GraphicsMode # == class RotateAboutPoint_Command(Line_Command): GraphicsMode_class = RotateAboutPoint_GraphicsMode commandName = 'RotateAboutPoint' featurename = "Rotate About Point" # (I don't know if this featurename is ever user-visible; # if it is, it's probably wrong -- consider overriding # self.get_featurename() to return the value from the # prior command, if this is used as a temporary command. # The default implementation returns this constant # or (if it's not overridden in subclasses) something # derived from it. [bruce 071227]) from utilities.constants import CL_REQUEST command_level = CL_REQUEST def rotateAboutPoint(self): """ Rotates the selected entities along the specified vector, about the specified pivot point (pivot point it the starting point of the drawn vector. """ if len(self.mouseClickPoints) != self.mouseClickLimit: print_compact_stack("Rotate about point bug: mouseclick points != mouseclicklimit: ") return pivotPoint = self.mouseClickPoints[0] ref_vec_endPoint = self.mouseClickPoints[1] rot_vec_endPoint = self.mouseClickPoints[2] reference_vec = norm(ref_vec_endPoint - pivotPoint) lineVector = norm(rot_vec_endPoint - pivotPoint) #lineVector = endPoint - startPoint quat1 = Q(lineVector, reference_vec) #DEBUG Disabled temporarily . will not be used if dot(lineVector, reference_vec) < 0: theta = math.pi - quat1.angle else: theta = quat1.angle #TEST_DEBUG-- Works fine theta = quat1.angle rot_axis = cross(lineVector, reference_vec) if dot(lineVector, reference_vec) < 0: rot_axis = - rot_axis cross_prod_1 = norm(cross(reference_vec, rot_axis)) cross_prod_2 = norm(cross(lineVector, rot_axis)) if dot(cross_prod_1, cross_prod_2) < 0: quat2 = Q(rot_axis, theta) else: quat2 = Q(rot_axis, - theta) movables = self.graphicsMode.getMovablesForLeftDragging() self.assy.rotateSpecifiedMovables( quat2, movables = movables, commonCenter = pivotPoint) self.glpane.gl_update() return def _results_for_request_command_caller(self): """ @return: tuple of results to return to whatever "called" self as a "request command" [overrides Line_GraphicsMode method] @see: Line_Command._f_results_for_caller_and_prepare_for_new_input() """ #bruce 080801 split this out of former restore_gui method (now inherited). # note (updated 2008-09-26): superclass Line_Command.command_entered() # sets self._results_callback,and superclass command_will_exit() #calls it with this method's return value return () pass # end of class RotateAboutPoint_Command # end
NanoCAD-master
cad/src/temporary_commands/RotateAboutPoint_Command.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ TemporaryCommand.py -- provides several kinds of TemporaryCommand superclasses (so far, just TemporaryCommand_Overdrawing, used for Zoom/Pan/Rotate). @author: Mark, Bruce @version: $Id$ @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. @license: GPL """ from PyQt4.Qt import Qt from command_support.Command import Command, commonCommand from command_support.GraphicsMode import GraphicsMode, commonGraphicsMode # == useful pieces -- Command class TemporaryCommand_preMixin(commonCommand): """ A pre-Mixin class for Command subclasses which want to act as temporary commands. """ command_should_resume_prevMode = True #bruce 071011, to be revised (replaces need for customized Done method) #See Command.anyCommand for detailed explanation of the following flag command_has_its_own_PM = False pass # == useful pieces -- GraphicsMode class ESC_to_exit_GraphicsMode_preMixin(commonGraphicsMode): """ A pre-mixin class for GraphicsModes which overrides their keyPress method to call self.command.command_Done() when the ESC key is pressed if self.command.should_exit_when_ESC_key_pressed() returns true, or to call assy.selectNone otherwise, but which delegates all other keypresses to the superclass. """ def keyPress(self, key): # ESC - Exit our command, if it permits exit due to ESC key. if key == Qt.Key_Escape: if self.command.should_exit_when_ESC_key_pressed(): self.command.command_Done() else: self.glpane.assy.selectNone() else: #bruce 071012 bugfix: add 'else' to prevent letting superclass # also handle Key_Escape and do assy.selectNone. # I think that was a bug, since you might want to pan or zoom etc # in order to increase the selection. Other ways of changing # the viewpoint (eg trackball) don't deselect everything. super(ESC_to_exit_GraphicsMode_preMixin, self).keyPress(key) # Fixes bug 1172 (F1 key). mark 060321 return pass class Overdrawing_GraphicsMode_preMixin(commonGraphicsMode): """ A pre-mixin class for GraphicsModes which want to override their Draw_* methods to do the parent command's drawing (perhaps in addition to their own, if they subclass this and further extend its Draw_* methods, or if they do incremental OpenGL drawing in event handler methods). (If there is no parent command, which I think never happens given how this is used as of 071012, this will raise an exception when any of its Draw_* methods are called.) @see: related class Delegating_GraphicsMode """ #bruce 090310 revised this def Draw_preparation(self): self.parentGraphicsMode.Draw_preparation() def Draw_axes(self): self.parentGraphicsMode.Draw_axes() def Draw_other_before_model(self): self.parentGraphicsMode.Draw_other_before_model() def Draw_model(self): self.parentGraphicsMode.Draw_model() def Draw_other(self): # doing this fixes the bug in which Pan etc doesn't show the right things # for BuildCrystal or Extrude modes (e.g. bond-offset spheres in Extrude) self.parentGraphicsMode.Draw_other() def Draw_after_highlighting(self, pickCheckOnly = False): #bruce 090310 new feature (or bugfix) -- delegate this too self.parentGraphicsMode.Draw_after_highlighting(pickCheckOnly = pickCheckOnly) pass # == class _TemporaryCommand_Overdrawing_GM( ESC_to_exit_GraphicsMode_preMixin, Overdrawing_GraphicsMode_preMixin, GraphicsMode ): """ GraphicsMode component of TemporaryCommand_Overdrawing. Note: to inherit this, get it from TemporaryCommand_Overdrawing.GraphicsMode_class rather than inheriting it directly by name. """ pass class TemporaryCommand_Overdrawing( TemporaryCommand_preMixin, Command): """ Common superclass for temporary view-change commands such as the Pan, Rotate, and Zoom tools. Provides the declarations that make a command temporary, a binding from the Escape key to the Done method, and a Draw method which delegates to the Draw method of the saved parentCommand. In other respects, inherits behavior from Command and GraphicsMode. """ GraphicsMode_class = _TemporaryCommand_Overdrawing_GM __abstract_command_class = True featurename = "Undocumented Temporary Command" # (I don't know if this featurename is ever user-visible; # if it is, it's probably wrong -- consider overriding # self.get_featurename() to return the value from the # prior command. # The default implementation returns this constant # or (if it's not overridden in subclasses) something # derived from it. [bruce 071227]) pass # keep this around for awhile, to show how to set it up when we want the # same thing while converting larger old modes: # ### == temporary compatibility code (as is the use of commonXXX in the mixins above) ## ##from modes import basicMode ## ### now combine all the classes used to make TemporaryCommand_Overdrawing and its _GM class: ## ##class basicTemporaryCommand_Overdrawing( TemporaryCommand_preMixin, ## ESC_to_exit_GraphicsMode_preMixin, ## Overdrawing_GraphicsMode_preMixin, ## basicMode ): ## pass # end
NanoCAD-master
cad/src/temporary_commands/TemporaryCommand.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ Zoom in/out mode functionality. @author: Mark Sims @version: $Id$ @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @license: GPL """ from Numeric import exp from temporary_commands.TemporaryCommand import TemporaryCommand_Overdrawing # == GraphicsMode part class ZoomInOutMode_GM( TemporaryCommand_Overdrawing.GraphicsMode_class ): """ Custom GraphicsMode for use as a component of ZoomInOutMode. """ def leftDown(self, event): """ Event handler for LMB press event. @param event: A Qt mouse event. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ # Setup zoom operation self.prevY = event.y() return def leftDrag(self, event): """ Event handler for LMB drag event. @param event: A Qt mouse event. @type event: U{B{QMouseEvent}<http://doc.trolltech.com/4/qmouseevent.html>} """ dScale = .025 # This works nicely. Mark 2008-01-29. delta = self.prevY - event.y() self.prevY = event.y() factor = exp(dScale * delta) #print "y, py =", event.y(), self.prevY, ", delta =", delta, ", factor=", factor self.glpane.rescale_around_point(factor) self.glpane.gl_update() return def update_cursor_for_no_MB(self): # Fixes bug 1638. Mark 3/12/2006. """ Update the cursor for 'Zoom In/Out' mode. """ self.glpane.setCursor(self.win.ZoomInOutCursor) pass # == Command part class ZoomInOutMode(TemporaryCommand_Overdrawing): """ Encapsulates the Zoom In/Out functionality. """ # class constants commandName = 'ZOOMINOUT' featurename = "Zoom In/Out Tool" from utilities.constants import CL_VIEW_CHANGE command_level = CL_VIEW_CHANGE GraphicsMode_class = ZoomInOutMode_GM def command_enter_misc_actions(self): """ See superclass method for documentation """ self.win.zoomInOutAction.setChecked(True) def command_exit_misc_actions(self): """ See superclass method for documentation """ self.win.zoomInOutAction.setChecked(False) #END new command API methods============================================== # end
NanoCAD-master
cad/src/temporary_commands/ZoomInOutMode.py
NanoCAD-master
cad/src/temporary_commands/LineMode/__init__.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. @license: GPL History: Split this out of LineMode.py (and deprecated that class) TODOs: - Refactor/ expand snap code. Should all the snapping code be in its own module? - Need to discuss and derive various snap rules Examples: If 'theta_snap' between dragged line and the two reference enties is the same, then the snap should use the entity with shortest distance Should horizontal/vertical snap checks always be done before standard axis snap checks -- guess-- No. The current implementation however skips the standard axis snap check if the horizontal/vertical snap checks succeed. """ from utilities.constants import black, darkred, blue from utilities.prefs_constants import DarkBackgroundContrastColor_prefs_key from utilities.prefs_constants import cursorTextFontSize_prefs_key from geometry.VQT import vlen, norm, angleBetween, V, ptonline import foundation.env as env from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.CS_draw_primitives import drawsphere from commands.Select.Select_GraphicsMode import Select_GraphicsMode STARTPOINT_SPHERE_RADIUS = 1.0 STARTPOINT_SPHERE_DRAWLEVEL = 2 # == GraphicsMode part _superclass_for_GM = Select_GraphicsMode class Line_GraphicsMode( Select_GraphicsMode ): """ Custom GraphicsMode for use as a component of Line_Command. It's a temporary mode that draws temporary line with mouse click points as endpoints and then returns to the previous mode when the mouseClickLimit specified by the user is reached. @see: L{DnaLineMode} TODO: -Need further documentation. """ #Initial values of instance variables -- #The first end point of the line being drawn. #It gets initialized during left down -- endPoint1 = None #The second endpoint of the line. This gets constantly updated as you # free drag the mouse (bare motion) endPoint2 = None rubberband_line_width = 1 #thickness or 'width' for drawer.drawline endPoint1_sphereColor = darkred endPoint1_sphereOpacity = 0.5 _snapOn = False _snapType = '' _standardAxisVectorForDrawingSnapReference = None #Flag that determines whether the cursor text should be rendered in #self.Draw_other. Example: This class draws cursor text at the end of the draw #method. Subclass of this class (say DnaLine_GM) calls this Draw_other method #and then do some more drawing and then again want to draw the cursor text. #So that subclass can temporarily suppress cursor text. #@see: DnaLine_GM.Draw_other() _ok_to_render_cursor_text = True #cursor text. ##@@ todo: rename it to 'cursorText' -- Ninad text = '' #the drawing plane on which the line (or the structure in subclasses) #will be placed. plane = None def Enter_GraphicsMode(self): _superclass_for_GM.Enter_GraphicsMode(self) self._ok_to_render_cursor_text = True #Set the drawing plane to the one returned by self.getDrawingPlane() #subclasses override the implementation of self.getDrawingPlane() #@see self.setDrawingPlane(). self.plane = self.getDrawingPlane() def getDrawingPlane(self): """ Overridden in subclasses. Returns the reference plane on which the line will be drawn. The default immplementation returns None. @see: InsertDna_GraphicsMode.getDrawingPlane() """ return self.plane def setDrawingPlane(self, plane): """ Sets the plane on which the line will be drawn (in subclasses , this is the plane on which the structure will be created.) @see: InsertDna_GraphicsMode.jigLeftUp() @see: InsertDna_EditCommand.updateDrawingPlane() """ if isinstance(plane, self.win.assy.Plane): self.plane = plane else: self.plane = None def isSpecifyPlaneToolActive(self): """ Default implementation returns False. Subclasses can override this method. @see: DnaDuplex_Graphicsmode.isSpecifyPlaneToolActive() which overrides this method. """ return False def leftDown(self, event): """ Event handler for LMB press event. """ if self.isSpecifyPlaneToolActive(): #@@@BUGGY: Ideally _superclass.leftDown should take care of this. #but Select_GraphicsMode doesn't do that. obj = self.get_obj_under_cursor(event) if obj is None: # Cursor over empty space. self.emptySpaceLeftDown(event) return self.doObjectSpecificLeftDown(obj, event) return self._leftDown_determine_endPoint1(event) #NIY code that accepts highlighted atom center as the endPoint instead ##of always using the glpane depth. To be implemented ##if self.glpane.selobj is not None: ##if isinstance(selobj, Atom): ##self.endPoint1 = self.glpane.selobj.posn() if self._snapOn and self.endPoint2 is not None: # This fixes a bug. Example: Suppose the dna line is snapped to a # constraint during the bare motion and the second point is clicked # when this happens, the second clicked point is the new #'self.endPoint1' which needs to be snapped like we did for # self.endPoint2 in the bareMotion. Setting self._snapOn to False # ensures that the cursor is set to the simple Pencil cursor after # the click -- Ninad 2007-12-04 self.endPoint1 = self.snapLineEndPoint() self._snapOn = False self.command.mouseClickPoints.append(self.endPoint1) return def _leftDown_determine_endPoint1(self, event): """ Determine the line endpoint (self.endPoint1) during the leftDown event. Subclasses can override this method. """ plane = self.getDrawingPlane() if plane: self.endPoint1 = self.dragstart_using_plane_depth( event, plane ) else: #The endPoint1 and self.endPoint2 are the mouse points at the 'water' #surface. Soon, support will be added so that these are actually points #on a user specified reference plane. Also, once any temporary mode # begins supporting highlighting, we can also add feature to use # coordinates of a highlighted object (e.g. atom center) as endpoints # of the line farQ_junk, self.endPoint1 = self.dragstart_using_GL_DEPTH( event, always_use_center_of_view = True ) def bareMotion(self, event): """ Event handler for simple drag event. (i.e. the free drag without holding down any mouse button) @see: self.isSpecifyPlaneToolActive() @see: self.getDrawingPlane() @see: DnaDuplex_Graphicsmode.isSpecifyPlaneToolActive() """ if not self.isSpecifyPlaneToolActive(): if len(self.command.mouseClickPoints) > 0: plane = self.getDrawingPlane() if plane: self.endPoint2 = self.dragto( self.endPoint1, event, perp = norm(plane.getaxis())) else: self.endPoint2 = self.dragto( self.endPoint1, event) self.endPoint2 = self.snapLineEndPoint() self.update_cursor_for_no_MB() self.glpane.gl_update() value = _superclass_for_GM.bareMotion(self,event) #Needed to make sure that the cursor is updated properly when #the mouse is moved after the 'specify reference plane tool is #activated/deactivated self.update_cursor() return value def snapLineEndPoint(self): """ Snap the line to the specified constraints. To be refactored and expanded. @return: The new endPoint2 i.e. the moving endpoint of the rubberband line . This value may be same as previous or snapped so that it lies on a specified vector (if one exists) @rtype: B{A} """ endPoint2 = self._snapEndPointHorizontalOrVertical() if not self._snapOn: endPoint2 = self._snapEndPointToStandardAxis() pass return endPoint2 def _snapEndPointHorizontalOrVertical(self): """ Snap the second endpoint of the line (and thus the whole line) to the screen horizontal or vertical vectors. @return: The new endPoint2 i.e. the moving endpoint of the rubberband line . This value may be same as previous or snapped so that line is horizontal or vertical depending upon the angle it makes with the horizontal and vertical. @rtype: B{A} """ up = self.glpane.up down = self.glpane.down left = self.glpane.left right = self.glpane.right endPoint2 = self.endPoint2 snapVector = V(0, 0, 0) currentLineVector = norm(self.endPoint2 - self.endPoint1) theta_horizontal = angleBetween(right, currentLineVector) theta_vertical = angleBetween(up, currentLineVector) theta_horizontal_old = theta_horizontal theta_vertical_old = theta_vertical if theta_horizontal != 90.0: theta_horizontal = min(theta_horizontal, (180.0 - theta_horizontal)) if theta_vertical != 90.0: theta_vertical = min(theta_vertical, 180.0 - theta_vertical) theta = min(theta_horizontal, theta_vertical) if theta <= 2.0 and theta != 0.0: self._snapOn = True if theta == theta_horizontal: self._snapType = 'HORIZONTAL' if theta_horizontal == theta_horizontal_old: snapVector = right else: snapVector = left elif theta == theta_vertical: self._snapType = 'VERTICAL' if theta_vertical == theta_vertical_old: snapVector = up else: snapVector = down endPoint2 = self.endPoint1 + \ vlen(self.endPoint1 - self.endPoint2)*snapVector else: self._snapOn = False return endPoint2 def _snapEndPointToStandardAxis(self): """ Snap the second endpoint of the line so that it lies on the nearest axis vector. (if its close enough) . This functions keeps the uses the current rubberband line vector and just extends the second end point so that it lies at the intersection of the nearest axis vector and the rcurrent rubberband line vector. @return: The new endPoint2 i.e. the moving endpoint of the rubberband line . This value may be same as previous or snapped to lie on the nearest axis (if one exists) @rtype: B{A} """ x_axis = V(1, 0, 0) y_axis = V(0, 1, 0) z_axis = V(0, 0, 1) endPoint2 = self.endPoint2 currentLineVector = norm(self.endPoint2 - self.endPoint1) theta_x = angleBetween(x_axis, self.endPoint2) theta_y = angleBetween(y_axis, self.endPoint2) theta_z = angleBetween(z_axis, self.endPoint2) theta_x = min(theta_x, (180 - theta_x)) theta_y = min(theta_y, (180 - theta_y)) theta_z = min(theta_z, (180 - theta_z)) theta = min(theta_x, theta_y, theta_z) if theta < 2.0: if theta == theta_x: self._standardAxisVectorForDrawingSnapReference = x_axis elif theta == theta_y: self._standardAxisVectorForDrawingSnapReference = y_axis elif theta == theta_z: self._standardAxisVectorForDrawingSnapReference = z_axis endPoint2 = ptonline(self.endPoint2, V(0, 0, 0), self._standardAxisVectorForDrawingSnapReference) else: self._standardAxisVectorForDrawingSnapReference = None return endPoint2 def _drawSnapReferenceLines(self): """ Draw the snap reference lines as dotted lines. Example, if the moving end of the rubberband line is 'close enough' to a standard axis vector, that point is 'snapped' soi that it lies on the axis. When this is done, program draws a dotted line from origin to the endPoint2 indicating that the endpoint is snapped to that axis line. This method is called inside the self.Draw_other method. @see: self._snapEndPointToStandardAxis @see: self.Draw_other """ if self.endPoint2 is None: return if self._standardAxisVectorForDrawingSnapReference: drawline(blue, V(0, 0, 0), self.endPoint2, dashEnabled = True, stipleFactor = 4, width = 2) return def Draw_other(self): """ """ _superclass_for_GM.Draw_other(self) #This fixes NFR bug 2803 #Don't draw the Dna rubberband line if the cursor is over the confirmation #corner. But make sure to call superclass.Draw_other method before doing this #check because we need to draw the rest of the model in the graphics #mode!. @see: DnaLineMode_GM.Draw_other() which does similar thing to not #draw the rubberband line when the cursor is on the confirmation corner handler = self.o.mouse_event_handler if handler is not None and handler is self._ccinstance: ##### REVIEW: # # 1. This is probably incorrect in principle, as a way of # deciding what to draw. The mouse event handling methods # should set an attribute which directly specifies whether # the next call of Draw_other (or other Draw methods) # should draw the rubberband line or not. # (Or which affects the value of an access method, e.g. # something like self.should_draw_rubberband_lines().) # # 2. Why is update_cursor called here? Any call of update_cursor # inside a specific Draw method seems suspicious. # # 3. This needs refactoring to merge with common code in its # subclass DnaLineMode_GM, and to consider doing the same # thing in its other 3 subclasses. # # [bruce 090310 comments] self.update_cursor() return if self.endPoint2 is not None: if self.endPoint1: drawsphere(self.endPoint1_sphereColor, self.endPoint1, STARTPOINT_SPHERE_RADIUS, STARTPOINT_SPHERE_DRAWLEVEL, opacity = self.endPoint1_sphereOpacity ) drawline(env.prefs[DarkBackgroundContrastColor_prefs_key], self.endPoint1, self.endPoint2, width = self.rubberband_line_width, dashEnabled = True) self._drawSnapReferenceLines() if self._ok_to_render_cursor_text: self._drawCursorText() def _drawCursorText(self): """ """ if self.endPoint1 is None or self.endPoint2 is None: return self.text = '' #### REVIEW: why do we set an attribute here? That's very # suspicious in any drawing method. [bruce 090310 comment] textColor = black #Draw the text next to the cursor that gives info about #number of base pairs etc. So this class and its command class needs #cleanup. e.g. callbackMethodForCursorTextString should be simply #self.command.getCursorText() and like that. -- Ninad2008-04-17 if self.command and hasattr(self.command, 'callbackMethodForCursorTextString'): self.text, textColor = self.command.callbackMethodForCursorTextString( self.endPoint1, self.endPoint2) else: vec = self.endPoint2 - self.endPoint1 thetaString = self._getCursorText_angle(vec) distString = self._getCursorText_length(vec) if distString: #This could be a user preference. At the moment, subclasses #may return an empty string for distance. self.text = "%5.2fA, %s" % (dist, thetaString) else: self.text = "%s" % (thetaString,) self.glpane.renderTextNearCursor(self.text, textColor = textColor, fontSize = env.prefs[cursorTextFontSize_prefs_key]) def _getCursorText_length(self, vec): """ Subclasses may override this method. @see: self._drawCursorText() for details. """ dist = vlen(vec) return "%5.2A"%(dist) def _getCursorText_angle(self, vec): """ Subclasses may override this method. @see: self._drawCursorText() for details. """ thetaString = '' theta = self.glpane.get_angle_made_with_screen_right(vec) thetaString = "%5.2f deg"%(theta) return thetaString def leftUp(self, event): """ Event handler for Left Mouse button left-up event @see: Line_Command._f_results_for_caller_and_prepare_for_new_input() """ if self.isSpecifyPlaneToolActive(): if self.cursor_over_when_LMB_pressed == 'Empty Space': self.emptySpaceLeftUp(event) return obj = self.current_obj if obj is None: # Nothing dragged (or clicked); return. return self.doObjectSpecificLeftUp(obj, event) return if self.command.mouseClickLimit is None: if len(self.command.mouseClickPoints) == 2: self.endPoint2 = None self.command._f_results_for_caller_and_prepare_for_new_input() self.glpane.gl_update() return assert len(self.command.mouseClickPoints) <= self.command.mouseClickLimit if len(self.command.mouseClickPoints) == self.command.mouseClickLimit: self.endPoint2 = None self._snapOn = False self._standardAxisVectorForDrawingSnapReference = None self.glpane.gl_update() #Exit this GM's command (i.e. the command 'Line') self.command.command_Done() return def update_cursor_for_no_MB(self): """ Update the cursor for this mode. """ #self.glpane.setCursor(self.win.SelectAtomsCursor) if self._snapOn: if self._snapType == 'HORIZONTAL': self.glpane.setCursor(self.win.pencilHorizontalSnapCursor) elif self._snapType == 'VERTICAL': self.glpane.setCursor(self.win.pencilVerticalSnapCursor) else: self.glpane.setCursor(self.win.colorPencilCursor) def resetVariables(self): """ Reset instance variables. Typically used by self.command when the command is exited without the graphics mode knowing about it before hand Example: You entered line mode, started drawing line, and hit Done button. This exits the Graphics mode (without the 'leftup' which usually terminates the command *from Graphics mode') . In the above case, the command.command_will_exit() needs to tell its graphics mode about what just happened , so that all the assigned values get cleared and ready to use next time this graphicsMode is active. """ self.endPoint1 = None self.endPoint2 = None pass # end
NanoCAD-master
cad/src/temporary_commands/LineMode/Line_GraphicsMode.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @license: GPL History: Split this out of LineMode.py (and deprecated that class) TODOs: - Refactor/ expand snap code. Should all the snapping code be in its own module? - Need to discuss and derive various snap rules Examples: If 'theta_snap' between dragged line and the two reference enties is the same, then the snap should use the entity with shortest distance Should horizontal/vertical snap checks always be done before standard axis snap checks -- guess-- No. The current implementation however skips the standard axis snap check if the horizontal/vertical snap checks succeed. """ from commands.Select.Select_Command import Select_Command from temporary_commands.LineMode.Line_GraphicsMode import Line_GraphicsMode from utilities.debug import print_compact_traceback # == Command part class Line_Command(Select_Command): """ Encapsulates the Line_Command tool functionality. """ # class constants commandName = 'Line_Command' featurename = "Line Command" # (I don't know if this featurename is ever user-visible; # if it is, it's probably wrong -- consider overriding # self.get_featurename() to return the value from the # prior command, if this is used as a temporary command. # The default implementation returns this constant # or (if it's not overridden in subclasses) something # derived from it. [bruce 071227]) from utilities.constants import CL_REQUEST command_level = CL_REQUEST GraphicsMode_class = Line_GraphicsMode # Initial value for the instance variable. (Note that although it is assigned # an empty tuple, later it is assigned a list.) Empty tuple is just for # the safer implementation than an empty list. Also, it is not 'None' # because in Line_GraphicsMode.bareMotion, it does a check using # len(mouseClickPoints) mouseClickPoints = () command_should_resume_prevMode = True command_has_its_own_PM = False _results_callback = None #bruce 080801 def setParams(self, params): """ Assign values obtained from the parent mode to the instance variables of this command object. """ # REVIEW: I think this is only called from self.command_entered(), # and ought to be private or inlined. I revised it to accept a tuple # of length 1 rather than an int. If old code had bugs of calling it # from the wrong places (which pass tuples of length 5), those are # now tracebacks, but before were perhaps silent errors (probably # harmless). So if my analysis of possible callers is wrong, this # change might cause bugs. [bruce 080801] assert len(params) == 1 #bruce 080801 (self.mouseClickLimit,) = params def _f_results_for_caller_and_prepare_for_new_input(self): """ This is called only from GraphicsMode.leftUp() Give results for the caller of this request command and then prepare for next input (mouse click points) from the user. Note that this is called from Line_GraphiceMode.leftUp() only when the mouseClickLimit is not specified (i.e. the command is not exited automatically after 'n' number of mouseclicks) @see: Line_GraphiceMode.leftUp() @see: RotateAboutPoints_GraphiceMode.leftUp() """ if self._results_callback: # note: see comment in command_will_exit version of this code params = self._results_for_request_command_caller() self._results_callback( params) self.mouseClickPoints = [] self.graphicsMode.resetVariables() def _results_for_request_command_caller(self): """ @return: tuple of results to return to whatever "called" self as a "request command" [overridden in subclasses] @see: Line_Command._f_results_for_caller_and_prepare_for_new_input() @see: RotateAboutPoint_Command._results_for_request_command_caller() """ #bruce 080801 ### REVIEW: make this a Request Command API method?? return (self.mouseClickPoints,) def command_entered(self): super(Line_Command, self).command_entered() self.mouseClickPoints = [] self.glpane.gl_update() params, results_callback = self._args_and_callback_for_request_command() if params is not None: self.setParams(params) self._results_callback = results_callback # otherwise we were not called as a request command; # method above prints something in that case, for now ### else: # maybe: set default params? self._results_callback = None def command_will_exit(self): super(Line_Command, self).command_will_exit() if self._results_callback: # note: _results_callback comes from an argument to # callRequestCommand. Under the current command sequencer # API, it's important to # call the callback no matter how self is exited (except possibly # when self.commandSequencer.exit_is_forced). This code always # calls it. [bruce 080904 comment] params = self._results_for_request_command_caller() self._results_callback( params) #clear the list [bruce 080801 revision, not fully analyzed: always do this] self.mouseClickPoints = [] self.graphicsMode.resetVariables() return
NanoCAD-master
cad/src/temporary_commands/LineMode/Line_Command.py
NanoCAD-master
cad/src/graphics/__init__.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ draw_grid_lines.py - helper functions for drawing grid lines in OpenGL. @version: $Id$ History: someone wrote these in drawer.py bruce 071030 split them into a separate module to remove an import cycle. TODO: does drawer.drawGrid also belong here? """ # the imports from math vs. Numeric are as discovered in existing code # as of 2007/06/25 [when this was part of drawer.py]. from math import floor, ceil from Numeric import sqrt from OpenGL.GL import glBegin ##from OpenGL.GL import GL_BLEND ##from OpenGL.GL import glBlendFunc from OpenGL.GL import glCallList from OpenGL.GL import glClipPlane from OpenGL.GL import GL_CLIP_PLANE0 from OpenGL.GL import GL_CLIP_PLANE1 from OpenGL.GL import GL_CLIP_PLANE2 from OpenGL.GL import GL_CLIP_PLANE3 from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import glEnd from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_LINES from OpenGL.GL import GL_LINE_SMOOTH from OpenGL.GL import glLineStipple from OpenGL.GL import GL_LINE_STIPPLE from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GL import GL_SRC_ALPHA from OpenGL.GL import glTranslate from OpenGL.GL import glVertex3f from OpenGL.GL import glGenLists from OpenGL.GL import GL_COMPILE from OpenGL.GL import glNewList from OpenGL.GL import GL_LINE_STRIP from OpenGL.GL import glVertex3fv from OpenGL.GL import glEndList from OpenGL.GL import glColor3fv from utilities.constants import PLANE_ORIGIN_LOWER_LEFT from utilities.constants import PLANE_ORIGIN_LOWER_RIGHT from utilities.constants import PLANE_ORIGIN_UPPER_LEFT from utilities.constants import PLANE_ORIGIN_UPPER_RIGHT from utilities.constants import LABELS_ALONG_ORIGIN, LABELS_ALONG_PLANE_EDGES from graphics.drawing.drawers import drawtext from geometry.VQT import V from graphics.drawing.Font3D import Font3D from utilities.prefs_constants import NO_LINE, SOLID_LINE from utilities.prefs_constants import DASHED_LINE, DOTTED_LINE SiCGridList = None # TODO: make this private # SiC grid geometry. The number in parentheses is the point's index in # the sic_vpdat list. This stuff is used to build an OpenGL display # list, indexed by SiCGridList. The repeating drawing unit is the # lines shown dotted here. The 1-6 line is omitted because it will be # supplied by the unit below. # # | # 2*sic_yU --+ (3) . . . . . (4) # | . . # | . . # | . . # | . . # | . . # sic_yU -(0) . . . . . (2) (5) # | . . # | . . # | . . # | . . # | . . # 0 --+------+------|-----(1)-----|-----(6)-----|--- # | | | | # 0 sic_uLen 2*sic_uLen 3*sic_uLen # sic_uLen = 1.8 # Si-C bond length (I think) sic_yU = sic_uLen * sqrt(3.0) / 2 sic_vpdat = [[0.0 * sic_uLen, 1.0 * sic_yU, 0.0], [1.5 * sic_uLen, 0.0 * sic_yU, 0.0], [1.0 * sic_uLen, 1.0 * sic_yU, 0.0], [1.5 * sic_uLen, 2.0 * sic_yU, 0.0], [2.5 * sic_uLen, 2.0 * sic_yU, 0.0], [3.0 * sic_uLen, 1.0 * sic_yU, 0.0], [2.5 * sic_uLen, 0.0 * sic_yU, 0.0]] def setup_draw_grid_lines(): """ This must be called in whichever GL display list context will be drawn in. See comment in drawer.setup_drawer about problems with calling this in more than one GL context. For now, it shouldn't be. """ global SiCGridList SiCGridList = glGenLists(1) glNewList(SiCGridList, GL_COMPILE) glBegin(GL_LINES) glVertex3fv(sic_vpdat[0]) glVertex3fv(sic_vpdat[2]) glEnd() glBegin(GL_LINE_STRIP) for v in sic_vpdat[1:]: glVertex3fv(v) glEnd() glEndList() return def drawGPGrid(glpane, color, line_type, w, h, uw, uh, up, right): """ Draw grid lines for a Grid Plane. glpane = the glpane color = grid line and unit text color line_type is: 0=None, 1=Solid, 2=Dashed or 3=Dotted w = width h = height uw = width spacing between grid lines uh = height spacing between grid lines """ if line_type == NO_LINE: return if uw > w: uw = w if uh > h: uh = h Z_OFF = 0.0 #0.001 glDisable(GL_LIGHTING) glColor3fv(color) hw = w/2.0; hh = h/2.0 #glEnable(GL_LINE_SMOOTH) #glEnable(GL_BLEND) #glBlendFunc(GL_SRC_ALPHA, GL_ONE)#_MINUS_SRC_ALPHA) if line_type > 1: glEnable(GL_LINE_STIPPLE) if line_type == DASHED_LINE: glLineStipple (1, 0x00FF) # dashed elif line_type == DOTTED_LINE: glLineStipple (1, 0x0101) # dotted else: print "drawGPGrid(): line_type '", line_type, \ "' is not valid. Drawing dashed grid line." glLineStipple (1, 0x00FF) # dashed glBegin(GL_LINES) #Draw horizontal lines y1 = 0 while y1 > -hh: glVertex3f(-hw, y1, Z_OFF) glVertex3f(hw, y1, Z_OFF) y1 -= uh y1 = 0 while y1 < hh: glVertex3f(-hw, y1, Z_OFF) glVertex3f(hw, y1, Z_OFF) y1 += uh #Draw vertical lines x1 = 0 while x1 < hw: glVertex3f(x1, hh, Z_OFF) glVertex3f(x1, -hh, Z_OFF) x1 += uw x1 = 0 while x1 > -hw: glVertex3f(x1, hh, Z_OFF) glVertex3f(x1, -hh, Z_OFF) x1 -= uw glEnd() if line_type > 1: glDisable (GL_LINE_STIPPLE) # Draw unit labels for gridlines (in nm). text_color = color import sys if sys.platform == "darwin": # WARNING: Anything smaller than 9 pt on Mac OS X results in # un-rendered text. Not sure why. -- piotr 080616 font_size = 9 else: font_size = 8 text_offset = 0.5 # Offset from edge of border, in Angstroms. # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 > -hh: y1 -= uh drawtext("%g" % (-y1 / 10.0), text_color, V(hw + text_offset, y1, 0.0), font_size, glpane) drawtext("%g" % (-y1 / 10.0), text_color, V(hw + text_offset, y1, 0.0), font_size, glpane) y1 = 0 while y1 < hh: drawtext("%g" % (-y1 / 10.0), text_color, V(hw + text_offset, y1, 0.0), font_size, glpane) y1 += uh drawtext("%g" % (-y1 / 10.0), text_color, V(hw + text_offset, y1, 0.0), font_size, glpane) # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 < hw: drawtext("%g" % (x1 / 10.0), text_color, V(x1, hh + text_offset, 0.0), font_size, glpane) x1 += uw drawtext("%g" % (x1 / 10.0), text_color, V(x1, hh + text_offset, 0.0), font_size, glpane) x1 = 0 while x1 > -hw: drawtext("%g" % (x1 / 10.0), text_color, V(x1, hh + text_offset, 0.0), font_size, glpane) x1 -= uw drawtext("%g" % (x1 / 10.0), text_color, V(x1, hh + text_offset, 0.0), font_size, glpane) glEnable(GL_LIGHTING) return def drawGPGridForPlane(glpane, color, line_type, w, h, uw, uh, up, right, displayLabels, originLocation, labelsDisplayStyle): """ Draw grid lines for a Grid from Plane PM. glpane = the glpane color = grid line and unit text color line_type is: 0=None, 1=Solid, 2=Dashed, or 3=Dotted w = width h = height uw = width spacing between grid lines uh = height spacing between grid lines """ if line_type == NO_LINE: return if uw > w: uw = w if uh > h: uh = h Z_OFF = 0.0 #0.001 glDisable(GL_LIGHTING) glColor3fv(color) hw = w/2.0; hh = h/2.0 if line_type > 1: glEnable(GL_LINE_STIPPLE) if line_type == DASHED_LINE: glLineStipple (1, 0x00FF) # dashed elif line_type == DOTTED_LINE: glLineStipple (1, 0x0101) # dotted else: print "drawGPGrid(): line_type '", line_type,"' is not valid. ", \ "Drawing dashed grid line." glLineStipple (1, 0x00FF) # dashed glBegin(GL_LINES) #Draw horizontal lines y1 = 0 while y1 > -hh: glVertex3f(-hw, y1, Z_OFF) glVertex3f(hw, y1, Z_OFF) y1 -= uh y1 = 0 while y1 < hh: glVertex3f(-hw, y1, Z_OFF) glVertex3f(hw, y1, Z_OFF) y1 += uh #Draw vertical lines x1 = 0 while x1 < hw: glVertex3f(x1, hh, Z_OFF) glVertex3f(x1, -hh, Z_OFF) x1 += uw x1 = 0 while x1 > -hw: glVertex3f(x1, hh, Z_OFF) glVertex3f(x1, -hh, Z_OFF) x1 -= uw glEnd() if line_type > 1: glDisable (GL_LINE_STIPPLE) # Draw unit labels for gridlines (in nm). text_color = color import sys if sys.platform == "darwin": # WARNING: Anything smaller than 9 pt on Mac OS X results in # un-rendered text. Not sure why. -- piotr 080616 font_size = 9 else: font_size = 8 text_offset = 0.3 # Offset from edge of border, in Angstroms. if displayLabels == True: if (originLocation == PLANE_ORIGIN_LOWER_LEFT and labelsDisplayStyle == LABELS_ALONG_ORIGIN): displayLabelsAlongOriginLowerLeft(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane) elif (originLocation == PLANE_ORIGIN_UPPER_LEFT and labelsDisplayStyle == LABELS_ALONG_ORIGIN): displayLabelsAlongOriginUpperLeft(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane) elif (originLocation == PLANE_ORIGIN_UPPER_RIGHT and labelsDisplayStyle == LABELS_ALONG_ORIGIN): displayLabelsAlongOriginUpperRight(h, w, hh, hw, uh, uw, text_offset, text_color,font_size, glpane) elif (originLocation == PLANE_ORIGIN_LOWER_RIGHT and labelsDisplayStyle == LABELS_ALONG_ORIGIN): displayLabelsAlongOriginLowerRight(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane) elif (originLocation == PLANE_ORIGIN_LOWER_LEFT and labelsDisplayStyle == LABELS_ALONG_PLANE_EDGES): displayLabelsAlongPlaneEdgesLowerLeft(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane) elif (originLocation == PLANE_ORIGIN_UPPER_LEFT and labelsDisplayStyle == LABELS_ALONG_PLANE_EDGES): displayLabelsAlongPlaneEdgesUpperLeft(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane) elif (originLocation == PLANE_ORIGIN_UPPER_RIGHT and labelsDisplayStyle == LABELS_ALONG_PLANE_EDGES): displayLabelsAlongPlaneEdgesUpperRight(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane) elif (originLocation == PLANE_ORIGIN_LOWER_RIGHT and labelsDisplayStyle == LABELS_ALONG_PLANE_EDGES): displayLabelsAlongPlaneEdgesLowerRight(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane) glEnable(GL_LIGHTING) return # UM 20080617: Code for displaying labels depending on origin location def displayLabelsAlongOriginLowerRight(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane): """ Display labels when origin is on the lower right corner. @param h: height of the plane @type h: float @param w: width of the plane @type w: float @param hh: half the height of the plane @type hh: float @param hw: half the width of the plane @type hw: float @param uh: spacing along height of the plane @type uh: float @param uw: spacing along width of the plane @type uw: float @param text_offset: offset for label @type text_offset: float @param text_color: color of the text @type: text_colot: tuple @param font_size: size of the text font @type: font_size: float @param glpane: The 3D graphics area to draw it in. @type glpane: L{GLPane} """ # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 >= -h: drawtext("%g" % (-y1 / 10.0), text_color, V(hw + text_offset, y1 + hh, 0.0), font_size, glpane) y1 -= uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 >= -w: drawtext("%g" % (-x1 / 10.0), text_color, V(x1 + hw, hh + 2 * text_offset, 0.0), font_size, glpane) x1 -= uw return def displayLabelsAlongOriginUpperLeft(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane): """ Display labels when origin is on the upper left corner. @param h: height of the plane @type h: float @param w: width of the plane @type w: float @param hh: half the height of the plane @type hh: float @param hw: half the width of the plane @type hw: float @param uh: spacing along height of the plane @type uh: float @param uw: spacing along width of the plane @type uw: float @param text_offset: offset for label @type text_offset: float @param text_color: color of the text @type: text_colot: tuple @param font_size: size of the text font @type: font_size: float @param glpane: The 3D graphics area to draw it in. @type glpane: L{GLPane} """ # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 <= h: drawtext("%g" % (y1 / 10.0), text_color, V(-hw - 3 * text_offset, y1 - hh, 0.0), font_size, glpane) y1 += uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 <= w: drawtext("%g" % (x1 / 10.0), text_color, V(x1 - hw, -hh - text_offset, 0.0), font_size, glpane) x1 += uw return def displayLabelsAlongOriginLowerLeft(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane): """ Display labels when origin is on the lower left corner. @param h: height of the plane @type h: float @param w: width of the plane @type w: float @param hh: half the height of the plane @type hh: float @param hw: half the width of the plane @type hw: float @param uh: spacing along height of the plane @type uh: float @param uw: spacing along width of the plane @type uw: float @param text_offset: offset for label @type text_offset: float @param text_color: color of the text @type: text_colot: tuple @param font_size: size of the text font @type: font_size: float @param glpane: The 3D graphics area to draw it in. @type glpane: L{GLPane} """ # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 >= -h: drawtext("%g" % (-y1 / 10.0), text_color, V(-hw - 3 * text_offset, y1 + hh, 0.0), font_size, glpane) y1 -= uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 <= w: drawtext("%g" % (x1 / 10.0), text_color, V(x1 - hw, hh + 2 * text_offset, 0.0), font_size, glpane) x1 += uw return def displayLabelsAlongOriginUpperRight(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane): """ Display Labels when origin is on the upper right corner. @param h: height of the plane @type h: float @param w: width of the plane @type w: float @param hh: half the height of the plane @type hh: float @param hw: half the width of the plane @type hw: float @param uh: spacing along height of the plane @type uh: float @param uw: spacing along width of the plane @type uw: float @param text_offset: offset for label @type text_offset: float @param text_color: color of the text @type: text_colot: tuple @param font_size: size of the text font @type: font_size: float @param glpane: The 3D graphics area to draw it in. @type glpane: L{GLPane} """ # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 <= h: drawtext("%g" % (y1 / 10.0), text_color, V(hw + text_offset, y1 - hh, 0.0), font_size, glpane) y1 += uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 >= -w: drawtext("%g" % (-x1 / 10.0), text_color, V(x1 + hw, - hh - text_offset, 0.0), font_size, glpane) x1 -= uw return def displayLabelsAlongPlaneEdgesLowerLeft(h, w ,hh, hw, uh, uw, text_offset, text_color, font_size, glpane): """ Display labels when origin is on the lower left corner. along all the plane edges @param h: height of the plane @type h: float @param w: width of the plane @type w: float @param hh: half the height of the plane @type hh: float @param hw: half the width of the plane @type hw: float @param uh: spacing along height of the plane @type uh: float @param uw: spacing along width of the plane @type uw: float @param text_offset: offset for label @type text_offset: float @param text_color: color of the text @type: text_colot: tuple @param font_size: size of the text font @type: font_size: float @param glpane: The 3D graphics area to draw it in. @type glpane: L{GLPane} """ #Along the origin edges # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 >= -h: drawtext("%g" % (-y1 / 10.0), text_color, V(-hw - 3 * text_offset, y1 + hh, 0.0), font_size, glpane) y1 -= uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 <= w: drawtext("%g" % (x1 / 10.0), text_color, V(x1 - hw, hh + 2 * text_offset, 0.0), font_size, glpane) x1 += uw #Along the non origin edges # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 >= -h: drawtext("%g" % (-y1 / 10.0), text_color, V(hw + 2 * text_offset, y1 + hh, 0.0), font_size, glpane) y1 -= uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 <= w: drawtext("%g" % (x1 / 10.0), text_color, V(x1 - hw, -hh - text_offset, 0.0), font_size, glpane) x1 += uw return def displayLabelsAlongPlaneEdgesUpperLeft(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane): """ Display labels along plane edges when origin is on the upper left corner. @param h: height of the plane @type h: float @param w: width of the plane @type w: float @param hh: half the height of the plane @type hh: float @param hw: half the width of the plane @type hw: float @param uh: spacing along height of the plane @type uh: float @param uw: spacing along width of the plane @type uw: float @param text_offset: offset for label @type text_offset: float @param text_color: color of the text @type: text_colot: tuple @param font_size: size of the text font @type: font_size: float @param glpane: The 3D graphics area to draw it in. @type glpane: L{GLPane} """ #Along origin edges # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 <= h: drawtext("%g" % (y1 / 10.0), text_color, V(-hw - 3 * text_offset, y1-hh, 0.0), font_size, glpane) y1 += uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 <= w: drawtext("%g" % (x1 / 10.0), text_color, V(x1 - hw, -hh - text_offset, 0.0), font_size, glpane) x1 += uw #Along non origin edges # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 <= h: drawtext("%g" % (y1 / 10.0), text_color, V(hw + 2 * text_offset, y1 - hh, 0.0), font_size, glpane) y1 += uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 <= w: drawtext("%g" % (x1 / 10.0), text_color, V(x1 - hw, hh + 2 * text_offset, 0.0), font_size, glpane) x1 += uw return def displayLabelsAlongPlaneEdgesLowerRight(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane): """ Display labels along plane edges when origin is on the lower right corner @param h: height of the plane @type h: float @param w: width of the plane @type w: float @param hh: half the height of the plane @type hh: float @param hw: half the width of the plane @type hw: float @param uh: spacing along height of the plane @type uh: float @param uw: spacing along width of the plane @type uw: float @param text_offset: offset for label @type text_offset: float @param text_color: color of the text @type: text_colot: tuple @param font_size: size of the text font @type: font_size: float @param glpane: The 3D graphics area to draw it in. @type glpane: L{GLPane} """ #Along origin edges # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 >= -h: drawtext("%g" % (-y1 / 10.0), text_color, V(hw + 2 * text_offset, y1 + hh, 0.0), font_size, glpane) y1 -= uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 >= -w: drawtext("%g" % (-x1 / 10.0), text_color, V(x1 + hw, hh + 2 * text_offset, 0.0), font_size, glpane) x1 -= uw #Along non origin edges # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 >= -h: drawtext("%g" % (-y1 / 10.0), text_color, V(-hw - 3 * text_offset, y1 + hh, 0.0), font_size, glpane) y1 -= uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 >= -w: drawtext("%g" % (-x1 / 10.0), text_color, V(x1 + hw, - hh - text_offset, 0.0), font_size, glpane) x1 -= uw return def displayLabelsAlongPlaneEdgesUpperRight(h, w, hh, hw, uh, uw, text_offset, text_color, font_size, glpane): """ Display Labels along plane edges when origin is on the upper right corner @param h: height of the plane @type h: float @param w: width of the plane @type w: float @param hh: half the height of the plane @type hh: float @param hw: half the width of the plane @type hw: float @param uh: spacing along height of the plane @type uh: float @param uw: spacing along width of the plane @type uw: float @param text_offset: offset for label @type text_offset: float @param text_color: color of the text @type: text_colot: tuple @param font_size: size of the text font @type: font_size: float @param glpane: The 3D graphics area to draw it in. @type glpane: L{GLPane} """ #Along origin edges # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 <= h: drawtext("%g" % (y1 / 10.0), text_color, V(hw + text_offset, y1 - hh, 0.0), font_size, glpane) y1 += uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 >= -w: drawtext("%g" % (-x1 / 10.0), text_color, V(x1 + hw, - hh - text_offset, 0.0), font_size, glpane) x1 -= uw #Along non-origin edges # Draw unit text labels for horizontal lines (nm) y1 = 0 while y1 <= h: drawtext("%g" % (y1 / 10.0), text_color, V(-hw - 3 * text_offset, y1 - hh, 0.0), font_size, glpane) y1 += uh # Draw unit text labels for vertical lines (nm). x1 = 0 while x1 >= -w: drawtext("%g" % (-x1 / 10.0), text_color, V(x1 + hw, hh + 2 * text_offset, 0.0), font_size, glpane) x1 -= uw return def drawSiCGrid(color, line_type, w, h, up, right): """ Draw SiC grid. """ if line_type == NO_LINE: return XLen = sic_uLen * 3.0 YLen = sic_yU * 2.0 hw = w/2.0; hh = h/2.0 i1 = int(floor(-hw/XLen)) i2 = int(ceil(hw/XLen)) j1 = int(floor(-hh/YLen)) j2 = int(ceil(hh/YLen)) glDisable(GL_LIGHTING) glColor3fv(color) if line_type > 1: glEnable(GL_LINE_STIPPLE) if line_type == DASHED_LINE: glLineStipple (1, 0x00FF) # dashed elif line_type == DOTTED_LINE: glLineStipple (1, 0x0101) # dotted else: print "drawer.drawSiCGrid(): line_type '", line_type, \ "' is not valid. Drawing dashed grid line." glLineStipple (1, 0x00FF) # dashed glClipPlane(GL_CLIP_PLANE0, (1.0, 0.0, 0.0, hw)) glClipPlane(GL_CLIP_PLANE1, (-1.0, 0.0, 0.0, hw)) glClipPlane(GL_CLIP_PLANE2, (0.0, 1.0, 0.0, hh)) glClipPlane(GL_CLIP_PLANE3, (0.0, -1.0, 0.0, hh)) glEnable(GL_CLIP_PLANE0) glEnable(GL_CLIP_PLANE1) glEnable(GL_CLIP_PLANE2) glEnable(GL_CLIP_PLANE3) glPushMatrix() glTranslate(i1*XLen, j1*YLen, 0.0) for i in range(i1, i2): glPushMatrix() for j in range(j1, j2): glCallList(SiCGridList) glTranslate(0.0, YLen, 0.0) glPopMatrix() glTranslate(XLen, 0.0, 0.0) glPopMatrix() glDisable(GL_CLIP_PLANE0) glDisable(GL_CLIP_PLANE1) glDisable(GL_CLIP_PLANE2) glDisable(GL_CLIP_PLANE3) if line_type > 1: glDisable (GL_LINE_STIPPLE) xpos, ypos = hw, 0.0 f3d = Font3D(xpos=xpos, ypos=ypos, right=right, up=up, rot90=False, glBegin=False) for j in range(j1, j2): yoff = j * YLen if -hh < yoff + ypos < hh: f3d.drawString("%-.4g" % yoff, color=color, yoff=yoff) xpos, ypos = 0.0, hh f3d = Font3D(xpos=xpos, ypos=ypos, right=right, up=up, rot90=True, glBegin=False) for i in range(2*i1, 2*i2): yoff = i * (XLen/2) if -hw < yoff + xpos < hw: f3d.drawString("%-.4g" % yoff, color=color, yoff=yoff) glEnable(GL_LIGHTING) return # end
NanoCAD-master
cad/src/graphics/drawing/draw_grid_lines.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ DrawingSet.py -- Top-level API for drawing with batched primitives (spheres, cylinders, cones) supported by specialized OpenGL shader programs. @author: Russ @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: Originally written by Russ Fish; designed together with Bruce Smith. ================================================================ See design comments on: * GL contexts, CSDLs and DrawingSet in DrawingSet.py * TransformControl in TransformControl.py * VBOs, IBOs, and GLPrimitiveBuffer in GLPrimitiveBuffer.py * GLPrimitiveSet in GLPrimitiveSet.py == GL context == Currently NE1 uses multiple GL contexts, but they all share large GL server state objects such as display lists, textures and VBOs. If this ever changes, we'll need an explicit object to manage each separate context with independent GL server state. For now (in both prior NE1 code and in this proposal), we use global variables for this, including a single global pool of CSDLs, TransformControls, and DrawingSets. This global pool can be considered an implicit singleton object. It has no name in this proposal. == CSDL (ColorSortedDisplayList) changes to support the new graphics design == * CSDLs are 'filled' or 'refilled' by streaming a set of drawing primitives into them. * Some drawing primitive types are supported by VBO batching in the graphics card RAM and shader programs, on some platforms. * In that case, the drawing primitive types and parameters are now saved by the ColorSorter front-end, as well as allocated primitive IDs once they're drawn. * Other primitive types go down though the ColorSorter into OpenGL Display Lists, as before. == DrawingSet == * A DrawingSet holds a set (dictionary) of CSDLs and has a draw() method with arguments like CSDL.draw: (highlighted = False, selected = False, patterning = True, highlight_color = None). * CSDLs can be efficiently added to or removed from a DrawingSet. * Each DrawingSet is allowed to contain an arbitrary subset of the global pool of CSDLs. Specifically, it's ok if one CSDL is in more than one DrawingSet, and if some but not all the CSDLs in one TransformControl are in one DrawingSet. * A DrawingSet caches a GLPrimitiveSet that consolidates the VBO-implemented primitives from the CSDLs, maintaining indices of primitive IDs to selectively draw large batches of primitives out of IBO/VBO hunks. * Optimization: There are several styles of using glMultiDrawElements with these indices of primitives that allow drawing arbitrary subsets efficiently in one GL call (per VBO hunk, per primitive type). * CSDLs now contain a change counter that causes (parts of) the GLPrimitiveSet indices to be lazily updated before a DrawingSet.draw . * When CSDLs are refilled, their batched drawing primitives are first freed, and then re-allocated in a stable order. """ from graphics.drawing.GLPrimitiveSet import GLPrimitiveSet class DrawingSet: """ Manage a set of CSDLs to be repeatedly drawn together. @note: self.CSDLs is a public member, but readonly for public use. It's a dict of our current CSDLs (mapping csdl.csdl_id to csdl), modified immediately by our methods which change our set of CSDLs. """ def __init__(self, csdl_list = ()): """ @param csdl_list: Optional initial CSDL list. """ # Use the integer IDs of the CSDLs as keys in a dictionary. # # The "set" type is not used here, since it was introduced in Python # 2.4, and we still support 2.3. # # Could also use id(csdl) as keys, but it's easier to understand with # small integer IDs when debugging, and runs twice as fast too. self.CSDLs = dict([(csdl.csdl_id, csdl) for csdl in csdl_list]) # client can modify this set later, using various methods # Cache a GLPrimitiveSet to speed drawing. # This must be reset to None whenever we modify self.CSDLs. self._primSet = None def destroy(self): #bruce 090218 self._primSet = None self.CSDLs = {} return # == # A subset of the set-type API. def addCSDL(self, csdl): """ Add a CSDL to the DrawingSet. No error if it's already present. @see: set_CSDLs, to optimize multiple calls. """ if csdl.csdl_id not in self.CSDLs: self.CSDLs[csdl.csdl_id] = csdl self._primSet = None pass return def removeCSDL(self, csdl): """ Remove a CSDL from the DrawingSet. Raises KeyError if not present. @see: set_CSDLs, to optimize multiple calls. """ del self.CSDLs[csdl.csdl_id] # may raise KeyError self._primSet = None return def discardCSDL(self, csdl): # (note: not presently used) """ Discard a CSDL from the DrawingSet, if present. No error if it isn't. """ if csdl.csdl_id in self.CSDLs: del self.CSDLs[csdl.csdl_id] self._primSet = None pass return # == def set_CSDLs(self, csdldict): #bruce 090226 """ Change our set of CSDLs (self.CSDLs) to csdldict, which we now own and might modify destructively (though the present implem doesn't do that), doing necessary invalidations or updates, in an optimal way. (Both self.CSDLs and csdldict are dictionaries which map csdl.csdl_id to csdl, to represent a set of CSDLs.) This is faster than figuring out and doing separate calls of removeCSDL and addCSDL, but is otherwise equivalent. It's allowed for csdldict to be empty. Self is not destroyed in that case, though all its CSDLs are removed. What we should optimize for: old and new csdldicts are either identical, or similar (large and mostly overlapping). """ have = self.CSDLs remove = dict(have) # modified below, by removing what we want, # thus leaving what we don't want add = {} # modified below, by adding what we want but don't have # question: is it more efficient to start with all we want, # then remove what we already have (usually removing fewer)? # in that case we'd start with csdldict, which we own. # guess: it's not more efficient, since add is usually smaller # than half of want (we assume). for csdl_id in csdldict.iterkeys(): # we want csdl_id; do we have it? csdl_if_have = remove.pop(csdl_id, None) if csdl_if_have is not None: # we want it and already have it -- don't remove it # (we're done, since we just popped it from remove) # (note that a csdl_id might be 0, so don't do a boolean test) pass else: # we want it but don't have it, so add it # (we optim for this set being small, so we don't # iterate over items, but look up csdl instead) # (we keep 'add' separate partly so we know whether it's # empty or not. review: whether it's more efficient to # set a flag and store csdl directly into self.CSDLs here. # Note that in future we might have to do more work # to each one we add, so that revision is probably # bad then, even if it's ok now.) add[csdl_id] = csdldict[csdl_id] continue # now remove and add are correct if remove: for csdl_id in remove.iterkeys(): del have[csdl_id] # modifies self.CSDLs self._primSet = None if add: have.update(add) self._primSet = None return # == def draw(self, highlighted = False, selected = False, patterning = True, highlight_color = None, opacity = 1.0): """ Draw the set of CSDLs in the DrawingSet. """ # Note: see similar code in CSDL.draw. # note: we do nothing about CSDLs whose transformControl has changed # since the last draw. This is not needed # when the transformControl is a Chunk, and I won't bother to # (re)implement it for now when using deprecated class # TransformControl. This will make TCs do nothing in their # test cases in test_drawing. [bruce 090223 revision] # See if any of the CSDLs has changed (in primitive content, not in # transformControl value) more recently than the _primSet and # clear the _primSet cache if so. (Possible optimization: regenerate # only some affected parts of the _primSet.) if self._primSet is not None: for csdl in self.CSDLs.itervalues(): if csdl.changed > self._primSet.created: self._primSet = None break continue pass # Lazily (re)generate the _primSet when needed for drawing. ##### REVIEW: does it copy any coordinates? [i don't think so] # if so, fix updateTransform somehow. [bruce 090224 comment] if self._primSet is None: self._primSet = GLPrimitiveSet(self.CSDLs.values()) pass # Draw the shader primitives and the OpenGL display lists. self._primSet.draw( highlighted, selected, patterning, highlight_color, opacity) return pass # end of class DrawingSet # end
NanoCAD-master
cad/src/graphics/drawing/DrawingSet.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ texture_fonts.py -- OpenGL fonts based on texture images of the characters @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. """ import os from OpenGL.GL import glTranslatef from OpenGL.GL import GL_TEXTURE_2D from OpenGL.GL import glBindTexture from OpenGL.GLU import gluProject from OpenGL.GLU import gluUnProject import foundation.env as env from utilities.icon_utilities import image_directory # for finding texture files from geometry.VQT import V, A, vlen from exprs.draw_utils import draw_textured_rect, mymousepoints from graphics.drawing.texture_helpers import load_image_into_new_texture_name from graphics.drawing.texture_helpers import setup_to_draw_texture_name # TODO: clean up -- these are defined in multiple files ORIGIN = V(0,0,0) DX = V(1,0,0) DY = V(0,1,0) DZ = V(0,0,1) # == class _attrholder: pass try: vv # singleton texture object ### TODO: rename, make an object except: vv = _attrholder() vv.tex_name = 0 vv.tex_data = None vv.have_mipmaps = False # == constants related to our single hardcoded texture-font # (these should be turned into instance attributes of a texture-font object) # Font image file (same image file is used in other modules, but for different # purposes.) ## ## CAD_SRC_PATH = os.path.dirname(__file__) ## from constants import CAD_SRC_PATH ## courierfile = os.path.join(CAD_SRC_PATH, ## "experimental/textures/courier-128.png") courierfile = os.path.join( image_directory(), "ui/exprs/text/courier-128.png") ### TODO: RENAME #e put these into an object for a texture font! tex_width = 6 # pixel width of 1 char within the texture image tex_height = 10 # pixel height (guess) """ ()() ()()(8) 8888 -- there's one more pixel of vertical space between the chars, here in idlehack, than in my courier-128.png image file! """ # == def ensure_courierfile_loaded(): #e rename to reflect binding too """ Load font-texture if we edited the params for that in this function, or didn't load it yet; bind it for drawing Anything that calls this should eventually call glpane.kluge_reset_texture_mode_to_work_around_renderText_bug(), but only after all drawing using the texture is done. """ tex_filename = courierfile ## "xxx.png" # the charset "courierfile" tex_data = (tex_filename,) if vv.tex_name == 0 or vv.tex_data != tex_data: vv.have_mipmaps, vv.tex_name = load_image_into_new_texture_name( tex_filename, vv.tex_name) vv.tex_data = tex_data else: pass # assume those vars are fine from last time setup_to_draw_texture_name(vv.have_mipmaps, vv.tex_name) return # kluge 061125 so exprs/images.py won't mess up drawfont2; might be slow def _bind_courier_font_texture(): """ assuming everything else is set up as needed, including that exprs/images.py doesn't change most GL params, bind the texture containing the courierfile font """ #bruce 070706 Bugfix for when drawfont2 is used outside of testmode. ensure_courierfile_loaded() # this requires a later call of # glpane.kluge_reset_texture_mode_to_work_around_renderText_bug() # which is done in our sole caller, drawfont2 [bruce 081205] # optimized part of inlined setup_to_draw_texture_name glBindTexture(GL_TEXTURE_2D, vv.tex_name) ##e note: this will need extension once images.py can change more params, # to do some of the other stuff now done by setup_to_draw_texture_name. # OTOH it's too expensive to do that all the time (and maybe even this, if # same tex already bound -- remains to be seen). return def drawfont2(glpane, msg = None, charwidth = None, charheight = None, testpattern = False, pixelwidth = None): """ Draws a rect of chars (dimensions given as char counts: charwidth x charheight [#e those args are misnamed] using vv's font texture [later 061113: assumed currently bound, i think -- see ensure_courierfile_loaded()], in a klugy way; msg gives the chars to draw (lines must be shorter than charwidth or they will be truncated) """ _bind_courier_font_texture() # adjust these guessed params (about the specific font image we're using as # a texture) until they work right: # (tex_origin_chars appears lower down, since it is revised there) tex_size = (128,128) # tex size in pixels tex_nx = 16 # number of chars in a row, in the tex image tex_ny = 8 # number of chars in a column if msg is None: msg = "(redraw %d)" % env.redraw_counter charwidth = tex_nx charheight = tex_ny + 1 lines = msg.split('\n') # tab not supported if charwidth is None: charwidth = 14 # could be max linelength plus 1 if charheight is None: charheight = len(lines) if not testpattern: while len(lines) < charheight: lines.append('') # draw individual chars from font-texture, # but first, try to position it so they look perfect (which worked for a # while, but broke sometime before 060728) ## glTranslatef( 0, pixelheight / 2, 0 ) # perfect! # (Ortho mode, home view, a certain window size -- not sure if that # matters but it might) # restoring last-saved window position (782, 44) and size (891, 749) ## gap = 2 # in pixels - good for debugging # good for looking nice! but note that idlehack uses one extra pixel of # vspace, and that does probably look better. gap = 0 # to do that efficiently i'd want another image to start from. # (or to modify this one to make the texture, by moving pixrects around) pixfactor = 1 # try *2... now i can see some fuzz... what if i start at origin, to draw? # Did that, got it tolerable for pixfactor 2, then back to 1 and i've lost # the niceness! Is it no longer starting at origin? ##pixelwidth = pixelheight = 0.05 * 2/3 #070124 revisions, general comment... current caveats/bugs: #### # - Only tested in Ortho mode. # - Working well but the bugs depend on whether we add "1 or" before # "pixelwidth is None" in if statement below: # Bugs when it computes pixelwidth here (even when passed, as always in # these tests): # - Textlabel for "current redraw" (in exprs/test.py bottom_left_corner) # disappears during highlighting. # Bugs when it doesn't [usual state & state I'll leave it in]: # - Not tested with displists off, maybe. ### # - Fuzzy text in testexpr_18 [not yet understood.] # - [fixed] Fuzzy text in "current redraw" textlabel during anything's # highlighting. [Fixed by removing DisplayListChunk from that.] # - [No bug in clarity of text in highlighted checkbox prefs themselves.] # - Works with displists on or off now. # - Is disable_translate helping?? Not sure (only matters when it computes # pixelwidth here -- not now.) # - ##e Use direct drawing_phase test instead? doesn't seem to be needed # anymore, from remaining bugs listed above. disable_translate = False #070124 #061211 permit caller to pass it [note: the exprs module usually or always # passes it, acc'd to test 070124] if pixelwidth is None: p1junk, p2a = mymousepoints(glpane, 10, 10) p1junk, p2b = mymousepoints(glpane, 11, 10) px,py,pz = vec = p2b - p2a # should be DX * pixelwidth ## print px,py,pz ### 0.0313971755382 0.0 0.0 (in Ortho mode, near but not at home view, ### also at it (??)) # 0.0313971755382 0.0 0.0 home ortho # 0.03139613018 0.0 0.0 home perspective -- still looks good (looks # the same) (with false "smoother textures") ## pixelwidth = pixelheight = px * pixfactor # 061211 Work better for rotated text (still not good unless # screen-parallel.) pixelwidth = pixelheight = vlen(vec) * pixfactor # print "pixelwidth",pixelwidth ####@@@@ can be one of: # 0.0319194157846 # or 0.0313961295259 # or 0.00013878006302 if pixelwidth < 0.01: # print "low pixelwidth:",pixelwidth, glpane.drawing_phase # e.g. 0.000154639183832 glselect pixelwidth = 0.0319194157846 ### kluge, in case you didn't notice [guess: formula is wrong during # highlighting] but this failed to fix the bug in which a TextRect # doesn't notice clicks unless you slide onto it from a Rect # ####@@@@ # Q 070124: when this happens (presumably due to small window in # glSelect) should we disable glTranslatef below? # I guess yes, so try it. Not that it'll help when we re-disable # always using this case. disable_translate = True # I'll leave this in since it seems right, but it's not obviously # helping by test. pass else: pixelheight = pixelwidth tex_origin_chars = V(3, 64) # revised 070124 #070124 -- note that disable_translate is never set given if statements #above -- if 1 and not disable_translate: ##e Use glpane.drawing_phase == 'glselect' instead? doesn't seem to ## be needed anymore, from remaining bugs listed above. # Translate slightly to make characters clearer (since we're still too # lazy to use glDrawPixels or whatever it's called). # Caveats: # - Assumes we're either not in a displist, or it's always drawn in the # same place. # - Will only work if we're drawing at correct depth for pixelwidth, I # presume -- and of course, parallel to screen. x,y,depth = gluProject(0.0, 0.0, 0.0) # Where we'd draw without any correction (ORIGIN). # Change x and y to a better place to draw (in pixel coords on screen.) # (note: This int(x+0.5) was compared by test to int(x) and int(x)+0.5 # -- this is best, as one might guess; not same for y...) ## if we need a "boldface kluge", using int(x)+0.5 here would be one... x = int(x+0.5) ### NOT UNDERSTOOD: Why x & y differ, in whether it's best to add this ### 0.5. y = int(y+0.5)+0.5 # [btw I'd guessed y+0.5 in int() should be (y-0.5)+0.5 due to outer # +0.5, but that looks worse in checkbox_pref centering; I don't know # why.] # [later, 080521: could it be +0.5 effect differing for x & y due to # different sign, since int() rounds towards zero rather than # towards neginf? ### REVIEW: fix this using intRound?] # # Adding outer 0.5 to y became best after I fixed a bug of # translating before glu*Project (just before this if-statement), # which fails inside displists since the translate effect doesn't # show up in glu*Project then. # # I wonder if the x/y difference could be related to the use of # CenterY around TextRect inside displists, which ought to produce a # similar bug if the shift is not by an exact number of pixels # (which is surely the case since the caller is guessing pixelwidth # as a hardcoded constant, IIRC). So the guess is that caller's # pixelwidth is wrong and/or CenterY shifts by an odd number of # halfpixels, inside displist and not seen by this glu*Project, # causing a bug which this +0.5 sometimes compensates for, but not # always due to pixelwidth being wrong. It's not worth # understanding this compared to switching over to glDrawPixels or # whatever it's called. ###DO THAT SOMETIME. p1 = A(gluUnProject(x, y, depth)) # where we'd like to draw (p1) # Test following code -- with this line, it should make us draw # noticeably higher up the screen -- works. ## p1 += DY glTranslatef( p1[0], p1[1], p1[2]) # fyi: NameError if we try glTranslatefv or glTranslatev -- didn't # look for other variants or in gl doc. pass tex_dx = V(tex_width, 0) # in pixels tex_dy = V(0, tex_height) # Using those guesses, come up with tex-rects for each char as triples of # 2-vectors (tex_origin, tex_dx, tex_dy). # i for y, j or x (is that order normal??), still starting at bottom left def ff(i,j): """ Which char to draw at this position? i is y, going up, -1 is lowest line (sorry.) """ nlines = len(lines) bottom = -1 # Change this api sometime. # This one too -- caller ought to be able to use 0 or 1 for the top # (first) line. abovethat = i - bottom if abovethat < nlines: # Draw chars from lines. test = lines[nlines-1 - abovethat] # Few-day(?)-old comment [as of 060728], not sure why it's # exactly here, maybe since this tells when we redraw, but it # might be correct other than that: this shows that mouseover of # objects (pixels) w/o glnames causes redraws! I understand # glselect ones, but they should not be counted, and should not # show up on the screen, so I don't understand any good reason # for these visible ones to happen. #e To try to find out, we could also record compact_stack of the # first gl_update that caused this redraw... if j < len(test): # Replace i,j with new ones so as to draw those chars instead. ch1 = ord(test[j]) - 32 j = ch1 % tex_nx i = 5 - (ch1 / tex_nx) else: # Draw a blank instead. ch1 = 32 - 32 j = ch1 % tex_nx i = 5 - (ch1 / tex_nx) else: # Use i,j to index the texture, meaning, draw test chars, perhaps # the entire thing. pass return tex_origin_chars + i * tex_dy + j * tex_dx , tex_dx, tex_dy # Now think about where to draw all this... use a gap, but otherwise the # same layout. charwidth1 = tex_width * pixelwidth charheight1 = tex_height * pixelheight char_dx = (tex_width + gap) * pixelwidth char_dy = (tex_height + gap) * pixelheight def gg(i,j): return (ORIGIN + j * char_dx * DX + (i + 1) * char_dy * DY, charwidth1 * DX, charheight1 * DY) # Now draw them. if 1: #### for n in range(65): # Simulate delay of a whole page of chars. # Note, this is significantly slow even if we just draw 5x as many # chars! (range was -1,tex_ny == 8, length 9) - Note, increasing i goes # up on screen, not down! for i in range(-1, charheight - 1): for j in range(charwidth): # Was tex_nx == 16 origin, dx, dy = gg(i,j) # Where to draw this char ###k # Still in pixel ints. # What tex coords to use to find it? tex_origin, ltex_dx, ltex_dy = ff(i,j) # Kluge until i look up how to use pixels directly. tex_origin, ltex_dx, ltex_dy = 1.0/tex_size[0] \ * V(tex_origin, ltex_dx, ltex_dy) #print (origin, dx, dy, tex_origin, tex_dx, tex_dy) # Cool bug effect bfr 'l's here. draw_textured_rect(origin, dx, dy, tex_origin, ltex_dx, ltex_dy) # draw some other ones? done above, with test string inside ff function. # Interesting q -- if i use vertex arrays or displist-index arrays, can # drawing 10k chars be fast? (guess: yes.) # Some facts: this window now has 70 lines, about 135 columns... of course # it's mostly blank, and in fact just now it has about 3714 chars, not 70 * # 135 = 9450 as if it was nowhere blank. # Above we draw 9 * 16 = 144, so ratio is 3714 / 144 = 25, or 9450 / 144 = # 65. # Try 65 redundant loops above & see what happens. It takes it a couple # seconds! Too slow! Of course it's mostly the py code. # Anyway, it means we *will* have to do one of those optims mentioned, or # some other one like not clearing/redrawing the entire screen during most # text editing, or having per-line display lists. glpane.kluge_reset_texture_mode_to_work_around_renderText_bug() return #drawfont2 #e rename, clean up
NanoCAD-master
cad/src/graphics/drawing/texture_fonts.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ drawers.py - Miscellaneous drawing functions that are not used as primitives. @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originated by Josh as drawer.py Various developers extended it since then. At some point Bruce partly cleaned up the use of display lists. 071030 bruce split some functions and globals into draw_grid_lines.py and removed some obsolete functions. 080519 russ pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py """ # the imports from math vs. Numeric are as discovered in existing code # as of 2007/06/25. It's not clear why acos is coming from math... from math import floor, ceil, acos import Numeric from Numeric import pi import foundation.env as env from OpenGL.GL import GL_BACK from OpenGL.GL import glBegin from OpenGL.GL import GL_BLEND from OpenGL.GL import glBlendFunc from OpenGL.GL import glCallList from OpenGL.GL import glColor3f from OpenGL.GL import glColor3fv from OpenGL.GL import glColor4fv from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import glDepthMask from OpenGL.GL import GL_DEPTH_TEST from OpenGL.GL import glDisable from OpenGL.GL import glDisableClientState from OpenGL.GL import glDrawElements from OpenGL.GL import glEnable from OpenGL.GL import glEnableClientState from OpenGL.GL import glEnd from OpenGL.GL import GL_FALSE from OpenGL.GL import GL_FILL from OpenGL.GL import GL_FLOAT from OpenGL.GL import GL_FRONT from OpenGL.GL import GL_FRONT_AND_BACK from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_LINE from OpenGL.GL import GL_LINE_LOOP from OpenGL.GL import GL_LINES from OpenGL.GL import glLineStipple from OpenGL.GL import GL_LINE_STIPPLE from OpenGL.GL import GL_LINE_STRIP from OpenGL.GL import glLineWidth from OpenGL.GL import glMatrixMode from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import glNormal3fv from OpenGL.GL import GL_ONE_MINUS_SRC_ALPHA from OpenGL.GL import glPointSize from OpenGL.GL import GL_POINTS from OpenGL.GL import GL_POINT_SMOOTH from OpenGL.GL import GL_POLYGON from OpenGL.GL import glPolygonMode from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushMatrix from OpenGL.GL import GL_QUADS from OpenGL.GL import glRotate from OpenGL.GL import glRotatef from OpenGL.GL import GL_SRC_ALPHA from OpenGL.GL import glTexCoord2fv from OpenGL.GL import GL_TEXTURE_2D from OpenGL.GL import glTranslate from OpenGL.GL import glTranslatef from OpenGL.GL import GL_TRIANGLES from OpenGL.GL import GL_TRUE from OpenGL.GL import GL_UNSIGNED_BYTE from OpenGL.GL import glVertex from OpenGL.GL import glVertex3f from OpenGL.GL import glVertex3fv from OpenGL.GL import GL_VERTEX_ARRAY from OpenGL.GL import glVertexPointer from OpenGL.GL import GL_COLOR_MATERIAL from OpenGL.GL import GL_TRIANGLE_STRIP from OpenGL.GL import glTexEnvf from OpenGL.GL import GL_TEXTURE_ENV from OpenGL.GL import GL_TEXTURE_ENV_MODE from OpenGL.GL import GL_MODULATE from OpenGL.GL import glNormalPointer from OpenGL.GL import glTexCoordPointer from OpenGL.GL import glDrawArrays from OpenGL.GL import GL_NORMAL_ARRAY from OpenGL.GL import GL_TEXTURE_COORD_ARRAY from geometry.VQT import norm, V, Q, A from utilities.constants import blue, red, darkgreen, black from utilities.prefs_constants import originAxisColor_prefs_key from utilities.prefs_constants import povAxisColor_prefs_key import graphics.drawing.drawing_globals as drawing_globals from graphics.drawing.gl_lighting import apply_material from graphics.drawing.gl_GLE import glePolyCone, gleGetNumSides, gleSetNumSides from graphics.drawing.gl_Scale import glScale, glScalef def drawCircle(color, center, radius, normal): """ Scale, rotate/translate the unit circle properly. """ glMatrixMode(GL_MODELVIEW) glPushMatrix() glColor3fv(color) glDisable(GL_LIGHTING) glTranslatef(center[0], center[1], center[2]) rQ = Q(V(0, 0, 1), normal) rotAngle = rQ.angle*180.0/pi #This may cause problems as proved before in Linear motor display. #rotation around (0, 0, 0) #if vlen(V(rQ.x, rQ.y, rQ.z)) < 0.00005: # rQ.x = 1.0 glRotatef(rotAngle, rQ.x, rQ.y, rQ.z) glScalef(radius, radius, 1.0) glCallList(drawing_globals.circleList) glEnable(GL_LIGHTING) glPopMatrix() return def drawFilledCircle(color, center, radius, normal): """ Scale, rotate/translate the unit circle properly. Added a filled circle variant, piotr 080405 """ glMatrixMode(GL_MODELVIEW) glPushMatrix() glColor3fv(color) glDisable(GL_LIGHTING) glTranslatef(center[0], center[1], center[2]) rQ = Q(V(0, 0, 1), normal) rotAngle = rQ.angle*180.0/pi #This may cause problems as proved before in Linear motor display. #rotation around (0, 0, 0) #if vlen(V(rQ.x, rQ.y, rQ.z)) < 0.00005: # rQ.x = 1.0 glRotatef(rotAngle, rQ.x, rQ.y, rQ.z) glScalef(radius, radius, 1.0) glCallList(drawing_globals.filledCircleList) glEnable(GL_LIGHTING) glPopMatrix() return def drawLinearArrows(longScale): glCallList(drawing_globals.linearArrowList) newPos = drawing_globals.halfHeight*longScale glPushMatrix() glTranslate(0.0, 0.0, -newPos) glCallList(drawing_globals.linearArrowList) glPopMatrix() glPushMatrix() glTranslate(0.0, 0.0, newPos -2.0*drawing_globals.halfEdge) glCallList(drawing_globals.linearArrowList) glPopMatrix() return def drawLinearSign(color, center, axis, l, h, w): """Linear motion sign on the side of squa-linder """ depthOffset = 0.005 glPushMatrix() glColor3fv(color) glDisable(GL_LIGHTING) glTranslatef(center[0], center[1], center[2]) ##Huaicai 1/17/05: To avoid rotate around (0, 0, 0), which causes ## display problem on some platforms angle = -acos(axis[2])*180.0/pi if (axis[2]*axis[2] >= 1.0): glRotate(angle, 0.0, 1.0, 0.0) else: glRotate(angle, axis[1], -axis[0], 0.0) glPushMatrix() glTranslate(h/2.0 + depthOffset, 0.0, 0.0) glPushMatrix() glScale(1.0, 1.0, l) glCallList(drawing_globals.linearLineList) glPopMatrix() if l < 2.6: sl = l/2.7 glScale(1.0, sl, sl) if w < 1.0: glScale(1.0, w, w) drawLinearArrows(l) glPopMatrix() glPushMatrix() glTranslate(-h/2.0 - depthOffset, 0.0, 0.0) glRotate(180.0, 0.0, 0.0, 1.0) glPushMatrix() glScale(1.0, 1.0, l) glCallList(drawing_globals.linearLineList) glPopMatrix() if l < 2.6: glScale(1.0, sl, sl) if w < 1.0: glScale(1.0, w, w) drawLinearArrows(l) glPopMatrix() glPushMatrix() glTranslate(0.0, w/2.0 + depthOffset, 0.0) glRotate(90.0, 0.0, 0.0, 1.0) glPushMatrix() glScale(1.0, 1.0, l) glCallList(drawing_globals.linearLineList) glPopMatrix() if l < 2.6: glScale(1.0, sl, sl) if w < 1.0: glScale(1.0, w, w) drawLinearArrows(l) glPopMatrix() glPushMatrix() glTranslate(0.0, -w/2.0 - depthOffset, 0.0 ) glRotate(-90.0, 0.0, 0.0, 1.0) glPushMatrix() glScale(1.0, 1.0, l) glCallList(drawing_globals.linearLineList) glPopMatrix() if l < 2.6: glScale(1.0, sl, sl) if w < 1.0: glScale(1.0, w, w) drawLinearArrows(l) glPopMatrix() glEnable(GL_LIGHTING) glPopMatrix() return def drawRotateSign(color, pos1, pos2, radius, rotation = 0.0): """Rotate sign on top of the caps of the cylinder """ glPushMatrix() glColor3fv(color) vec = pos2-pos1 axis = norm(vec) glTranslatef(pos1[0], pos1[1], pos1[2]) ##Huaicai 1/17/05: To avoid rotate around (0, 0, 0), which causes ## display problem on some platforms angle = -acos(axis[2])*180.0/pi if (axis[2]*axis[2] >= 1.0): glRotate(angle, 0.0, 1.0, 0.0) else: glRotate(angle, axis[1], -axis[0], 0.0) glRotate(rotation, 0.0, 0.0, 1.0) #bruce 050518 glScale(radius,radius,Numeric.dot(vec,vec)**.5) glLineWidth(2.0) glDisable(GL_LIGHTING) glCallList(drawing_globals.rotSignList) glEnable(GL_LIGHTING) glLineWidth(1.0) glPopMatrix() return def drawArrowHead(color, basePoint, drawingScale, unitBaseVector, unitHeightVector): arrowBase = drawingScale * 0.08 arrowHeight = drawingScale * 0.12 glDisable(GL_LIGHTING) glPushMatrix() glTranslatef(basePoint[0],basePoint[1],basePoint[2]) point1 = V(0, 0, 0) point1 = point1 + unitHeightVector * arrowHeight point2 = unitBaseVector * arrowBase point3 = - unitBaseVector * arrowBase #Draw the arrowheads as filled triangles glColor3fv(color) glBegin(GL_POLYGON) glVertex3fv(point1) glVertex3fv(point2) glVertex3fv(point3) glEnd() glPopMatrix() glEnable(GL_LIGHTING) def drawSineWave(color, startPoint, endPoint, numberOfPoints, phaseAngle): """ Unimplemented. """ pass def drawPolyLine(color, points): """ Draws a poly line passing through the given list of points """ glDisable(GL_LIGHTING) glColor3fv(color) glBegin(GL_LINE_STRIP) for v in points: glVertex3fv(v) glEnd() glEnable(GL_LIGHTING) return def drawPoint(color, point, pointSize = 3.0, isRound = True): """ Draw a point using GL_POINTS. @param point: The x,y,z coordinate array/ vector of the point @type point: A or V @param pointSize: The point size to be used by glPointSize @type pointSize: float @param isRound: If True, the point will be drawn round otherwise square @type isRound: boolean """ glDisable(GL_LIGHTING) glColor3fv(color) glPointSize(float(pointSize)) if isRound: glEnable(GL_POINT_SMOOTH) glBegin(GL_POINTS) glVertex3fv(point) glEnd() if isRound: glDisable(GL_POINT_SMOOTH) glEnable(GL_LIGHTING) if pointSize != 1.0: glPointSize(1.0) return def drawLineCube(color, pos, radius): vtIndices = [0,1,2,3, 0,4,5,1, 5,4,7,6, 6,7,3,2] glEnableClientState(GL_VERTEX_ARRAY) #bruce 051117 revised this glVertexPointer(3, GL_FLOAT, 0, drawing_globals.flatCubeVertices) #grantham 20051213 observations, reported/paraphrased by bruce 051215: # - should verify PyOpenGL turns Python float (i.e. C double) into C # float for OpenGL's GL_FLOAT array element type. # - note that GPUs are optimized for DrawElements types GL_UNSIGNED_INT # and GL_UNSIGNED_SHORT. glDisable(GL_LIGHTING) glColor3fv(color) glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) glScale(radius,radius,radius) glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_BYTE, vtIndices) #glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_BYTE, vtIndices[4]) #glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_BYTE, vtIndices[8]) #glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_BYTE, vtIndices[12]) glPopMatrix() glEnable(GL_LIGHTING) glDisableClientState(GL_VERTEX_ARRAY) return def drawwirecube(color, pos, radius, lineWidth = 3.0): glPolygonMode(GL_FRONT, GL_LINE) glPolygonMode(GL_BACK, GL_LINE) glDisable(GL_LIGHTING) glDisable(GL_CULL_FACE) glColor3fv(color) glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) if type(radius) == type(1.0): glScale(radius,radius,radius) else: glScale(radius[0], radius[1], radius[2]) glLineWidth(lineWidth) glCallList(drawing_globals.lineCubeList) glLineWidth(1.0) ## restore its state glPopMatrix() glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glPolygonMode(GL_FRONT, GL_FILL) #bruce 050729 to help fix bug 835 or related bugs glPolygonMode(GL_BACK, GL_FILL) return def drawwirebox(color, pos, length): glPolygonMode(GL_FRONT, GL_LINE) glPolygonMode(GL_BACK, GL_LINE) glDisable(GL_LIGHTING) glDisable(GL_CULL_FACE) glColor3fv(color) glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) glScale(length[0], length[1], length[2]) glCallList(drawing_globals.CubeList) glPopMatrix() glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glPolygonMode(GL_FRONT, GL_FILL) #bruce 050729 to help fix bug 835 or related bugs glPolygonMode(GL_BACK, GL_FILL) return def segstart(color): glDisable(GL_LIGHTING) glColor3fv(color) glBegin(GL_LINES) return def drawsegment(pos1,pos2): glVertex3fv(pos1) glVertex3fv(pos2) return def segend(): glEnd() glEnable(GL_LIGHTING) return def drawAxis(color, pos1, pos2, width = 2): #Ninad 060907 """ Draw chunk or jig axis """ #ninad060907 Note that this is different than draw # I may need this function to draw axis line. see its current implementation # in branch "ninad_060908_drawAxis_notAsAPropOfObject" glDisable(GL_LIGHTING) glColor3fv(color) glLineStipple(3, 0x1C47) # dash-dot-dash line glEnable(GL_LINE_STIPPLE) if width != 1: glLineWidth(width) glBegin(GL_LINES) glVertex(pos1[0], pos1[1], pos1[2]) glVertex(pos2[0], pos2[1], pos2[2]) glEnd() if width != 1: glLineWidth(1.0) # restore default state glDisable(GL_LINE_STIPPLE) glEnable(GL_LIGHTING) return def drawPointOfViewAxes(scale, point): """ Draw point of view (POV) axes. """ color = env.prefs[povAxisColor_prefs_key] drawaxes(scale * 0.1, point, color, coloraxes = False, dashEnabled = False) def drawaxes(scale, point, color = black, coloraxes = False, dashEnabled = False): """ Draw axes. @note: used for both origin axes and point of view axes. @see: drawOriginAsSmallAxis (related code) """ n = scale glPushMatrix() glTranslate(point[0], point[1], point[2]) glDisable(GL_LIGHTING) if dashEnabled: #ninad060921 Note that we will only support dotted origin axis #(hidden lines) but not POV axis. (as it could be annoying) glLineStipple(5, 0xAAAA) glEnable(GL_LINE_STIPPLE) glDisable(GL_DEPTH_TEST) glColor3fv(color) if coloraxes: glColor3fv(red) glBegin(GL_LINES) glVertex( n, 0, 0) glVertex(-n, 0, 0) if coloraxes: glColor3fv(darkgreen) glVertex(0, n, 0) glVertex(0, -n, 0) if coloraxes: glColor3fv(blue) glVertex(0, 0, n) glVertex(0, 0, -n) glEnd() if dashEnabled: glDisable(GL_LINE_STIPPLE) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glPopMatrix() return def drawOriginAsSmallAxis(scale, origin, dashEnabled = False): """ Draws a small wireframe version of the origin. It is rendered as a 3D point at (0, 0, 0) with 3 small axes extending from it in the positive X, Y, Z directions. @see: drawaxes (related code) """ #Perhaps we should split this method into smaller methods? ninad060920 #Notes: #1. drawing arrowheads implemented on 060918 #2. ninad060921 Show the origin axes as dotted if behind the mode. #3. ninad060922 The arrow heads are drawn as wireframe cones if behind the # object the arrowhead size is slightly smaller (otherwise some portion of # the the wireframe arrow shows up! #4 .Making origin non-zoomable is acheived by replacing hardcoded 'n' with # glpane's scale - ninad060922 #ninad060922 in future , the following could be user preferences. if (dashEnabled): dashShrinkage = 0.9 else: dashShrinkage = 1 x1, y1, z1 = scale * 0.01, scale * 0.01, scale * 0.01 xEnd, yEnd, zEnd = scale * 0.04, scale * 0.09, scale * 0.025 arrowBase = scale * 0.0075 * dashShrinkage arrowHeight = scale * 0.035 * dashShrinkage lineWidth = 1.0 glPushMatrix() glTranslate(origin[0], origin[1], origin[2]) glDisable(GL_LIGHTING) glLineWidth(lineWidth) gleNumSides = gleGetNumSides() #Code to show hidden lines of the origin if some model obscures it # ninad060921 if dashEnabled: glLineStipple(2, 0xAAAA) glEnable(GL_LINE_STIPPLE) glDisable(GL_DEPTH_TEST) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) gleSetNumSides(5) else: gleSetNumSides(10) glBegin(GL_LINES) color = env.prefs[originAxisColor_prefs_key] glColor3fv(color) #start draw a point at origin . #ninad060922 is thinking about using GL_POINTS here glVertex(-x1, 0.0, 0.0) glVertex( x1, 0.0, 0.0) glVertex(0.0, -y1, 0.0) glVertex(0.0, y1, 0.0) glVertex(-x1, y1, z1) glVertex( x1, -y1, -z1) glVertex(x1, y1, z1) glVertex(-x1, -y1, -z1) glVertex(x1, y1, -z1) glVertex(-x1, -y1, z1) glVertex(-x1, y1, -z1) glVertex(x1, -y1, z1) #end draw a point at origin #start draw small origin axes glColor3fv(color) glVertex(xEnd, 0.0, 0.0) glVertex( 0.0, 0.0, 0.0) glColor3fv(color) glVertex(0.0, yEnd, 0.0) glVertex(0.0, 0.0, 0.0) glColor3fv(color) glVertex(0.0, 0.0, zEnd) glVertex(0.0, 0.0, 0.0) glEnd() #end draw lines glLineWidth(1.0) # End push matrix for drawing various lines in the origin and axes. glPopMatrix() #start draw solid arrow heads for X , Y and Z axes glPushMatrix() glDisable(GL_CULL_FACE) glColor3fv(color) glTranslatef(xEnd, 0.0, 0.0) glRotatef(90, 0.0, 1.0, 0.0) glePolyCone([[0, 0, -1], [0, 0, 0], [0, 0, arrowHeight], [0, 0, arrowHeight+1]], None, [arrowBase, arrowBase, 0, 0]) glPopMatrix() glPushMatrix() glColor3fv(color) glTranslatef(0.0, yEnd, 0.0) glRotatef(-90, 1.0, 0.0, 0.0) glePolyCone([[0, 0, -1], [0, 0, 0], [0, 0, arrowHeight], [0, 0, arrowHeight+1]], None, [arrowBase, arrowBase, 0, 0]) glPopMatrix() glPushMatrix() glColor3fv(color) glTranslatef(0.0,0.0,zEnd) glePolyCone([[0, 0, -1], [0, 0, 0], [0, 0, arrowHeight], [0, 0, arrowHeight+1]], None, [arrowBase, arrowBase, 0, 0]) #Disable line stipple and Enable Depth test if dashEnabled: glLineStipple(1, 0xAAAA) glDisable(GL_LINE_STIPPLE) glEnable(GL_DEPTH_TEST) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) gleSetNumSides(gleNumSides) glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glPopMatrix() #end draw solid arrow heads for X , Y and Z axes return def findCell(pt, latticeType): """ Return the cell which contains the point <pt> """ if latticeType == 'DIAMOND': cellX = cellY = cellZ = drawing_globals.DiGridSp elif latticeType == 'LONSDALEITE': cellX = drawing_globals.XLen cellY = drawing_globals.YLen cellZ = drawing_globals.ZLen i = int(floor(pt[0]/cellX)) j = int(floor(pt[1]/cellY)) k = int(floor(pt[2]/cellZ)) orig = V(i*cellX, j*cellY, k*cellZ) return orig, drawing_globals.sp1 def genDiam(bblo, bbhi, latticeType): """ Generate a list of possible atom positions within the area enclosed by (bblo, bbhi). <Return>: A list of unit cells """ if latticeType == 'DIAMOND': a = 0 cellX = cellY = cellZ = drawing_globals.DiGridSp elif latticeType == 'LONSDALEITE': a = 1 cellX = drawing_globals.XLen cellY = drawing_globals.YLen cellZ = drawing_globals.ZLen allCells = [] for i in range(int(floor(bblo[0]/cellX)), int(ceil(bbhi[0]/cellX))): for j in range(int(floor(bblo[1]/cellY)), int(ceil(bbhi[1]/cellY))): for k in range(int(floor(bblo[2]/cellZ)), int(ceil(bbhi[2]/cellZ))): off = V(i*cellX, j*cellY, k*cellZ) if a == 0: allCells += [drawing_globals.digrid + off] elif a ==1: allCells += [drawing_globals.lonsEdges + off] return allCells def drawGrid(scale, center, latticeType): """ Construct the grid model and show as position references for cookies. The model is build around "pov" and has size of 2*"scale" on each of the (x, y, z) directions. @note: This should be optimized later. For "scale = 200", it takes about 1479623 loops. ---Huaicai """ glDisable(GL_LIGHTING) # bruce 041201: # Quick fix to prevent "hang" from drawing too large a BuildCrystal_Command grid # with our current cubic algorithm (bug 8). The constant 120.0 is still on # the large side in terms of responsiveness -- on a 1.8GHz iMac G5 it can # take many seconds to redraw the largest grid, or to update a selection # rectangle during a drag. I also tried 200.0 but that was way too large. # Since some users have slower machines, I'll be gentle and put 90.0 here. # Someday we need to fix the alg to be quadratic by teaching this code # (and the Crystal builder code too) about the eyespace clipping planes. # Once we support user prefs, this should be one of them (if the alg is # not fixed by then). MAX_GRID_SCALE = 90.0 if scale > MAX_GRID_SCALE: scale = MAX_GRID_SCALE if latticeType == 'DIAMOND': cellX = cellY = cellZ = drawing_globals.DiGridSp elif latticeType == 'LONSDALEITE': cellX = drawing_globals.XLen cellY = drawing_globals.YLen cellZ = drawing_globals.ZLen bblo = center - scale bbhi = center + scale i1 = int(floor(bblo[0]/cellX)) i2 = int(ceil(bbhi[0]/cellX)) j1 = int(floor(bblo[1]/cellY)) j2 = int(ceil(bbhi[1]/cellY)) k1 = int(floor(bblo[2]/cellZ)) k2 = int(ceil(bbhi[2]/cellZ)) glPushMatrix() glTranslate(i1*cellX, j1*cellY, k1*cellZ) for i in range(i1, i2): glPushMatrix() for j in range(j1, j2): glPushMatrix() for k in range(k1, k2): if latticeType == 'DIAMOND': glCallList(drawing_globals.diamondGridList) else: glCallList(drawing_globals.lonsGridList) glTranslate(0.0, 0.0, cellZ) glPopMatrix() glTranslate(0.0, cellY, 0.0) glPopMatrix() glTranslate(cellX, 0.0, 0.0) glPopMatrix() glEnable(GL_LIGHTING) #drawCubeCell(V(1, 0, 0)) return def drawrectangle(pt1, pt2, rt, up, color): """ Draws a (hollow) rectangle outline of the given I{color}. @param pt1: First corner of the rectangle. @type pt1: Point @param pt1: Opposite corner of the rectangle. @type pt1: Point @param rt: Right vector of the glpane. @type rt: Unit vector @param up: Right vector of the glpane. @type up: Unit vector @param color: Color @type color: color """ glColor3f(color[0], color[1], color[2]) glDisable(GL_LIGHTING) c2 = pt1 + rt * Numeric.dot(rt, pt2 - pt1) c3 = pt1 + up * Numeric.dot(up, pt2 - pt1) glBegin(GL_LINE_LOOP) glVertex(pt1[0], pt1[1], pt1[2]) glVertex(c2[0], c2[1], c2[2]) glVertex(pt2[0], pt2[1], pt2[2]) glVertex(c3[0], c3[1], c3[2]) glEnd() glEnable(GL_LIGHTING) #bruce & wware 060404: drawRubberBand apparently caused bug 1814 (Zoom Tool # hanging some Macs, requiring power toggle) so it should not be used until # debugged. Use drawrectangle instead. (For an example of how to translate # between them, see ZoomMode.py rev 1.32 vs 1.31 in ViewCVS.) That bug was only # repeatable on Bruce's & Will's iMacs G5. # # Bruce's speculations (not very definite; no evidence for them at all) about # possible causes of the bug in drawRubberBand: # - use of glVertex instead of glVertex3f or so??? This seems unlikely, since we # have other uses of it, but perhaps they work due to different arg types. # - use of GL_LINE_LOOP within OpenGL xor mode, and bugs in some OpenGL # drivers?? I didn't check whether BuildCrystal_Command does this too. ##def drawRubberBand(pt1, pt2, c2, c3, color): ## """Huaicai: depth test should be disabled to make the xor work """ ## glBegin(GL_LINE_LOOP) ## glVertex(pt1[0],pt1[1],pt1[2]) ## glVertex(c2[0],c2[1],c2[2]) ## glVertex(pt2[0],pt2[1],pt2[2]) ## glVertex(c3[0],c3[1],c3[2]) ## glEnd() ## return # Wrote drawbrick for the Linear Motor. Mark [2004-10-10] def drawbrick(color, center, axis, l, h, w, opacity = 1.0): if len(color) == 3: color = (color[0], color[1], color[2], opacity) if opacity != 1.0: glDepthMask(GL_FALSE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) apply_material(color) glPushMatrix() glTranslatef(center[0], center[1], center[2]) ##Huaicai 1/17/05: To avoid rotate around (0, 0, 0), which causes ## display problem on some platforms angle = -acos(axis[2])*180.0/pi if (axis[2]*axis[2] >= 1.0): glRotate(angle, 0.0, 1.0, 0.0) else: glRotate(angle, axis[1], -axis[0], 0.0) glScale(h, w, l) #bruce 060302 revised the contents of solidCubeList while fixing bug 1595 glCallList(drawing_globals.solidCubeList) if opacity != 1.0: glDisable(GL_BLEND) glDepthMask(GL_TRUE) glPopMatrix() return def drawLineLoop(color,lines, width = 1): glDisable(GL_LIGHTING) glColor3fv(color) glLineWidth(width) glBegin(GL_LINE_LOOP) for v in lines: glVertex3fv(v) glEnd() glEnable(GL_LIGHTING) #reset the glLineWidth to 1 if width!=1: glLineWidth(1) return def drawlinelist(color,lines): glDisable(GL_LIGHTING) glColor3fv(color) glBegin(GL_LINES) for v in lines: glVertex3fv(v) glEnd() glEnable(GL_LIGHTING) return cubeLines = A([[-1,-1,-1], [-1,-1, 1], [-1, 1,-1], [-1, 1, 1], [ 1,-1,-1], [ 1,-1, 1], [ 1, 1,-1], [ 1, 1, 1], [-1,-1,-1], [-1, 1,-1], [-1,-1, 1], [-1, 1, 1], [ 1,-1,-1], [ 1, 1,-1], [ 1,-1, 1], [ 1, 1, 1], [-1,-1,-1], [ 1,-1,-1], [-1,-1, 1], [ 1,-1, 1], [-1, 1,-1], [ 1, 1,-1], [-1, 1, 1], [ 1, 1, 1]]) def drawCubeCell(color): sp0 = drawing_globals.sp0 sp4 = drawing_globals.sp4 vs = [[sp0, sp0, sp0], [sp4, sp0, sp0], [sp4, sp4, sp0], [sp0, sp4, sp0], [sp0, sp0, sp4], [sp4, sp0, sp4], [sp4, sp4, sp4], [sp0, sp4, sp4]] glDisable(GL_LIGHTING) glColor3fv(color) glBegin(GL_LINE_LOOP) for ii in range(4): glVertex3fv(vs[ii]) glEnd() glBegin(GL_LINE_LOOP) for ii in range(4, 8): glVertex3fv(vs[ii]) glEnd() glBegin(GL_LINES) for ii in range(4): glVertex3fv(vs[ii]) glVertex3fv(vs[ii+4]) glEnd() glEnable(GL_LIGHTING) return def drawPlane(color, w, h, textureReady, opacity, SOLID = False, pickCheckOnly = False, tex_coords = None): """ Draw polygon with size of <w>*<h> and with color <color>. Optionally, it could be texuture mapped, translucent. @pickCheckOnly This is used to draw the geometry only, used for OpenGL pick selection purpose. @param tex_coords: texture coordinates to be explicitly provided (for simple image transformation purposes) """ vs = [[-0.5, 0.5, 0.0], [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.5, 0.5, 0.0]] # piotr 080529: use external texture coordinates if provided if tex_coords is None: vt = [[0.0, 1.0], [0.0, 0.0], [1.0, 0.0], [1.0, 1.0]] else: vt = tex_coords if textureReady: opacity = 1.0 glDisable(GL_LIGHTING) glColor4fv(list(color) + [opacity]) glPushMatrix() glScalef(w, h, 1.0) if SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glDisable(GL_CULL_FACE) if not pickCheckOnly: # This makes sure a translucent object will not occlude another # translucent object. glDepthMask(GL_FALSE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if textureReady: glEnable(GL_TEXTURE_2D) glBegin(GL_QUADS) for ii in range(len(vs)): t = vt[ii] v = vs[ii] if textureReady: glTexCoord2fv(t) glVertex3fv(v) glEnd() if not pickCheckOnly: if textureReady: glDisable(GL_TEXTURE_2D) glDisable(GL_BLEND) glDepthMask(GL_TRUE) glEnable(GL_CULL_FACE) if not SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPopMatrix() glEnable(GL_LIGHTING) return def drawHeightfield(color, w, h, textureReady, opacity, SOLID = False, pickCheckOnly = False, hf = None): """ Draw a heighfield using vertex and normal arrays. Optionally, it could be texture mapped. @pickCheckOnly This is used to draw the geometry only, used for OpenGL pick selection purpose. """ if not hf: # Return if heightfield is not provided return glEnable(GL_COLOR_MATERIAL) glEnable(GL_LIGHTING) # Don't use opacity, otherwise the heighfield polygons should be sorted # - something to implement later... ## glColor3v(list(color)) if textureReady: # For texturing, use white color (to be modulated by the texture) glColor3f(1,1,1) else: glColor3fv(list(color)) glPushMatrix() glScalef(w, h, 1.0) if SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glDisable(GL_CULL_FACE) if not pickCheckOnly: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if textureReady: glEnable(GL_TEXTURE_2D) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) for tstrip_vert, tstrip_norm, tstrip_tex in hf: glVertexPointer(3, GL_FLOAT, 0, tstrip_vert) glNormalPointer(GL_FLOAT, 0, tstrip_norm) glTexCoordPointer(2, GL_FLOAT, 0, tstrip_tex) glDrawArrays(GL_TRIANGLE_STRIP, 0, len(tstrip_vert)) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisable(GL_COLOR_MATERIAL) if not pickCheckOnly: if textureReady: glDisable(GL_TEXTURE_2D) glDepthMask(GL_TRUE) glEnable(GL_CULL_FACE) if not SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPopMatrix() glEnable(GL_LIGHTING) return def drawFullWindow(vtColors): """ Draw gradient background color. <vtColors> is a 4 element list specifying colors for the left-down, right-down, right-up, left-up window corners. To draw the full window, the modelview and projection should be set in identity. """ from utilities.constants import GL_FAR_Z glDisable(GL_LIGHTING) glBegin(GL_QUADS) glColor3fv(vtColors[0]) glVertex3f(-1, -1, GL_FAR_Z) glColor3fv(vtColors[1]) glVertex3f(1, -1, GL_FAR_Z) glColor3fv(vtColors[2]) glVertex3f(1, 1, GL_FAR_Z) glColor3fv(vtColors[3]) glVertex3f(-1, 1, GL_FAR_Z) glEnd() glEnable(GL_LIGHTING) return def drawtext(text, color, origin, point_size, glpane): """ """ # see also: _old_code_for_drawing_text() if not text: return glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) from PyQt4.Qt import QFont, QString ##, QColor font = QFont( QString("Helvetica"), point_size) #glpane.qglColor(QColor(75, 75, 75)) from widgets.widget_helpers import RGBf_to_QColor glpane.qglColor(RGBf_to_QColor(color)) glpane.renderText(origin[0], origin[1], origin[2], QString(text), font) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) return ### obsolete code: ### The following code used to be for drawing text on a QGLWidget -- ### some of it might still be useful if integrated into drawtext() above ### [moved here from elementColors.py and slightly cleaned up by bruce 080223] ##def _old_code_for_drawing_text(glpane): ## self = glpane ## glDisable(GL_LIGHTING) ## glDisable(GL_DEPTH_TEST) ## self.qglColor(QColor(0, 0, 0)) ## font = QFont( QString("Times"), 10) ## text = QString('Rvdw = ' + str(self.rad)) ## fontMecs = QFontMetrics(font) ## strWd = fontMecs.width(text) ## strHt = fontMecs.height() ## w = self.width/2 - strWd/2 ## h = self.height - strHt/2 ## self.renderText(w, h, text, font) ## glEnable(GL_DEPTH_TEST) ## glEnable(GL_LIGHTING) def renderSurface(surfaceEntities, surfaceNormals): ####@@@@ bruce 060927 comments: # - The color needs to come before the vertex. I fixed that, but left a # debug_pref that can change it so you can see the effect of that bug # before it was fixed. (Same for the normal, but it already did come # before.) # - I suspect normals are not used (when nc > 0) due to lighting being # off. But if it's on, colors are not used. I saw that problem before, # and we had to use apply_material instead, to set color; I'm not sure # why, it might just be due to specific OpenGL settings we make for other # purposes. So I'll use drawer.apply_material(color) (again with a debug # pref to control that). # The effect of the default debug_pref settings is that it now works # properly with color -- but only for the 2nd chunk, if you create two, and # not at all if you create only one. I don't know why it doesn't work for # the first chunk. (entityIndex, surfacePoints, surfaceColors) = surfaceEntities e0 = entityIndex[0] n = len(e0) nc = len(surfaceColors) if 1: ### bruce 060927 debug code; when done debugging, we can change them to ### constants & simplify the code that uses them. from utilities.debug_prefs import debug_pref, Choice_boolean_True from utilities.debug_prefs import Choice_boolean_False disable_lighting = debug_pref("surface: disable lighting?", Choice_boolean_False) if nc: color_first = debug_pref("surface: color before vertex?", Choice_boolean_True) use_apply_material = debug_pref("surface: use apply_material?", Choice_boolean_True) ## old code was equivalent to disable_lighting = (nc > 0) #bruce 060927 Split this out, so we can change how we apply color in a # single place in the code. def use_color(color): if use_apply_material: # This makes the colors visible even when lighting is enabled. apply_material(color) else: # Old code did this. These colors are only visible when lighting is # not enabled. glColor3fv(color) pass return #bruce 060927 Split this out, for code clarity, and so debug prefs are # used in only one place. def onevert(vertex_index): glNormal3fv(surfaceNormals[vertex_index]) # This needs to be done before glVertex3fv. if nc > 0 and color_first: use_color(surfaceColors[vertex_index]) glVertex3fv(surfacePoints[vertex_index]) # Old code did it here -- used wrong colors sometimes. if nc > 0 and not color_first: use_color(surfaceColors[vertex_index]) pass return ## if nc > 0 : ## glDisable(GL_LIGHTING) if disable_lighting: glDisable(GL_LIGHTING) if n == 3: glBegin(GL_TRIANGLES) for entity in entityIndex: onevert(entity[0]) onevert(entity[1]) onevert(entity[2]) glEnd() else: glBegin(GL_QUADS) for entity in entityIndex: onevert(entity[0]) onevert(entity[1]) onevert(entity[2]) onevert(entity[3]) glEnd() if disable_lighting: glEnable(GL_LIGHTING) return # end
NanoCAD-master
cad/src/graphics/drawing/drawers.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ Guides.py - Draws horizontal and vertical rulers along the edges of the 3D graphics area. @author: Mark Sims @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ @license: GPL """ from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushMatrix from OpenGL.GL import GL_BLEND from OpenGL.GL import glBegin from OpenGL.GL import glBlendFunc from OpenGL.GL import glColor3fv from OpenGL.GL import glColor4fv from OpenGL.GL import glDepthMask from OpenGL.GL import GL_DEPTH_TEST from OpenGL.GL import glEnd from OpenGL.GL import GL_FALSE from OpenGL.GL import GL_LINES from OpenGL.GL import glLoadIdentity from OpenGL.GL import glMatrixMode from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_TRUE from OpenGL.GL import glVertex from OpenGL.GL import glViewport from OpenGL.GLU import gluOrtho2D from OpenGL.GL import GL_SRC_ALPHA from OpenGL.GL import GL_ONE_MINUS_SRC_ALPHA from OpenGL.GL import glRectf from OpenGL.GL import GL_PROJECTION from OpenGL.GLU import gluUnProject # piotr 080326 from PyQt4.Qt import QFont, QFontMetrics, QString, QColor from widgets.widget_helpers import RGBf_to_QColor from geometry.VQT import V from utilities.constants import lightgray, darkgray, black from utilities.debug import print_compact_stack import sys import foundation.env as env from utilities.prefs_constants import displayVertRuler_prefs_key from utilities.prefs_constants import displayHorzRuler_prefs_key from utilities.prefs_constants import rulerPosition_prefs_key from utilities.prefs_constants import rulerColor_prefs_key from utilities.prefs_constants import rulerOpacity_prefs_key # These must match the order items appear in the ruler "Position" combobox # in the preferences dialog. _lower_left = 0 _upper_left = 1 _lower_right = 2 _upper_right = 3 def getRulerDrawingParameters(width, height, aspect, scale, zoomFactor, ruler_position): """ Compute and return all the ruler drawing parameters needed by draw(). @param width: Width of the 3D graphics area in pixels. @type width: int @param height: Height of the 3D graphics area in pixels. @type height: int @param aspect: The aspect ratio of the 3D graphics area (width / height) @type aspect: float @param scale: Half-height of the field of view in Angstroms. @type scale: float @param zoomFactor: Zoom factor. @type zoomFactor: float @param ruler_position: The ruler position, where: - 0 = lower left - 1 = upper left - 2 = lower right - 3 = upper right @type ruler_position: int """ # Note: Bruce's "drawRulers.py" review email (2008-02-24) includes # two good suggestions for making code in this method clearer and # more general. I plan to implement them when time allows, but it is # not urgent. --Mark. viewHeight = scale * zoomFactor * 2.0 # In Angstroms. # num_horz_ticks gets initialized here, but may get changed further below. # num_vert_ticks is set after num_horz_ticks is finally set. num_horz_ticks = int(viewHeight) tickmark_spacing = 1.0 / viewHeight * height tickmark_spacing_multiplier = 1.0 # This section computes the the tick mark drawing parameters based on # the viewHeight of the 3D graphics area. Be careful if you change these # values. Mark 2008-02-07 if viewHeight <= 5.5: units_text = "A" # Angstroms units_format = "%2d" units_scale = 1.0 unit_label_inc = 1 long_tickmark_inc = 10 medium_tickmark_inc = 5 elif viewHeight <= 20.1: units_text = "A" # Angstroms units_format = "%2d" units_scale = 1.0 unit_label_inc = 5 long_tickmark_inc = 10 medium_tickmark_inc = 5 elif viewHeight <= 50.1: units_text = "nm" # nanometers units_format = "%-3.1f" units_scale = 0.1 unit_label_inc = 5 long_tickmark_inc = 10 medium_tickmark_inc = 5 elif viewHeight <= 101.0: units_text = "nm" # nanometers units_format = "%2d" units_scale = 0.1 unit_label_inc = 10 long_tickmark_inc = 10 medium_tickmark_inc = 5 elif viewHeight <= 201.0: units_text = "nm" # nanometers units_format = "%2d" units_scale = .5 unit_label_inc = 2 long_tickmark_inc = 10 medium_tickmark_inc = 2 num_horz_ticks = int(num_horz_ticks * 0.2) tickmark_spacing_multiplier = 5.0 elif viewHeight <= 1001.0: units_text = "nm" # nanometers units_format = "%2d" units_scale = 1.0 unit_label_inc = 5 long_tickmark_inc = 10 medium_tickmark_inc = 5 num_horz_ticks = int(num_horz_ticks * 0.1) tickmark_spacing_multiplier = 10.0 elif viewHeight <= 2001.0: units_text = "nm" # nanometers units_format = "%2d" units_scale = 1.0 unit_label_inc = 10 long_tickmark_inc = 10 medium_tickmark_inc = 5 num_horz_ticks = int(num_horz_ticks * 0.1) tickmark_spacing_multiplier = 10.0 elif viewHeight <= 5005.0: units_text = "nm" # nanometers units_format = "%2d" units_scale = 2.0 unit_label_inc = 10 long_tickmark_inc = 10 medium_tickmark_inc = 5 num_horz_ticks = int(num_horz_ticks * 0.05) tickmark_spacing_multiplier = 20.0 elif viewHeight <= 10005.0: units_text = "Um" # micrometers units_format = "%-3.1f" units_scale = 0.01 unit_label_inc = 10 long_tickmark_inc = 10 medium_tickmark_inc = 5 num_horz_ticks = int(num_horz_ticks * 0.01) tickmark_spacing_multiplier = 100.0 elif viewHeight <= 30005.0: units_text = "Um" # micrometers units_format = "%-3.1f" units_scale = 0.1 unit_label_inc = 1 long_tickmark_inc = 10 medium_tickmark_inc = 5 num_horz_ticks = int(num_horz_ticks * 0.001) tickmark_spacing_multiplier = 1000.0 elif viewHeight <= 50005.0: units_text = "Um" # micrometers units_format = "%-3.1f" units_scale = 0.1 unit_label_inc = 5 long_tickmark_inc = 10 medium_tickmark_inc = 5 num_horz_ticks = int(num_horz_ticks * 0.001) tickmark_spacing_multiplier = 1000.0 else: units_text = "Um" # micrometers units_format = "%2d" units_scale = 0.1 unit_label_inc = 10 long_tickmark_inc = 10 medium_tickmark_inc = 5 num_horz_ticks = int(num_horz_ticks * 0.001) tickmark_spacing_multiplier = 1000.0 # Kludge alert. If viewHeight gets larger than 250000.0 (25 Um), set a # flag passed to draw() so that it won't draw tick marks and unit text # on rulers. if viewHeight > 250000.0: draw_ticks_and_text = False else: draw_ticks_and_text = True num_vert_ticks = int(num_horz_ticks * aspect) + 1 _DEBUG = False if _DEBUG: print "hr ticks=", num_horz_ticks, "vr ticks=", num_vert_ticks print "tickmark_spacing=", tickmark_spacing, "viewHeight=", viewHeight print "units_scale=", units_scale, "unit_label_inc=", unit_label_inc # Compute ruler width based on font size, which should be a user pref # for far-sighted users that need larger unit text in rulers. # Mark 2008-02-20 ruler_thickness = 15.0 vr_thickness = ruler_thickness hr_thickness = ruler_thickness vr_long_tick_len = vr_thickness * 0.75 vr_medium_tick_len = vr_thickness * 0.5 vr_short_tick_len = vr_thickness * 0.25 hr_long_tick_len = vr_thickness * 0.75 hr_medium_tick_len = vr_thickness * 0.5 hr_short_tick_len = vr_thickness * 0.25 if ruler_position == _lower_left: ruler_origin = V(0.0, 0.0, 0.0) #units_text_origin = V(3.0, 5.0, 0.0) # piotr 080326: moved the text origin to the cell center units_text_origin = ruler_origin + V(hr_thickness/2,vr_thickness/2,0.0) ruler_start_pt = ruler_origin \ + V(vr_thickness, hr_thickness, 0.0) origin_square_pt1 = V(0.0, 0.0, 0.0) origin_square_pt2 = V(vr_thickness, hr_thickness, 0.0) # VR vars. vr_rect_pt1 = V(0.0, hr_thickness, 0.0) vr_rect_pt2 = V(vr_thickness, height, 0.0) vr_line_pt1 = V(vr_thickness, 0.0, 0.0) vr_line_pt2 = V(vr_thickness, height, 0.0) vr_long_tick_len *= -1.0 vr_medium_tick_len *= -1.0 vr_short_tick_len *= -1.0 vr_units_x_offset = -vr_thickness vr_units_y_offset = 3.0 vr_tickmark_spacing = tickmark_spacing # HR vars. hr_rect_pt1 = V(vr_thickness, 0.0, 0.0) hr_rect_pt2 = V(width, hr_thickness, 0.0) hr_line_pt1 = V(0.0, hr_thickness, 0.0) hr_line_pt2 = V(width, hr_thickness, 0.0) hr_long_tick_len *= -1.0 hr_medium_tick_len *= -1.0 hr_short_tick_len *= -1.0 hr_units_x_offset = 3.0 hr_units_y_offset = -hr_thickness * 0.8 hr_tickmark_spacing = tickmark_spacing elif ruler_position == _upper_left: hr_thickness *= -1 # Note: Thickness is a negative value. ruler_origin = V(0.0, height, 0.0) #units_text_origin = ruler_origin \ # + V(3.0, hr_thickness + 4.0, 0.0) # piotr 080326: moved the text origin to the cell center units_text_origin = ruler_origin + V(vr_thickness/2,hr_thickness/2,0.0) ruler_start_pt = ruler_origin \ + V(vr_thickness, hr_thickness, 0.0) origin_square_pt1 = V(0.0, height + hr_thickness, 0.0) origin_square_pt2 = V(vr_thickness, height, 0.0) # VR vars. vr_rect_pt1 = V(0.0, 0.0, 0.0) vr_rect_pt2 = V(vr_thickness, height + hr_thickness, 0.0) vr_line_pt1 = V(vr_thickness, 0.0, 0.0) vr_line_pt2 = V(vr_thickness, height, 0.0) vr_long_tick_len *= -1.0 vr_medium_tick_len *= -1.0 vr_short_tick_len *= -1.0 vr_units_x_offset = -vr_thickness vr_units_y_offset = -10.0 # HR vars. hr_rect_pt1 = V(vr_thickness, height + hr_thickness, 0.0) hr_rect_pt2 = V(width, height, 0.0) hr_line_pt1 = V(0, height + hr_thickness, 0.0) hr_line_pt2 = V(width, height + hr_thickness, 0.0) hr_units_x_offset = 3.0 hr_units_y_offset = -hr_thickness * 0.5 vr_tickmark_spacing = -tickmark_spacing hr_tickmark_spacing = tickmark_spacing elif ruler_position == _lower_right: ruler_origin = V(width, 0.0, 0.0) vr_thickness *= -1 # Note: Thickness is a negative value. #units_text_origin = ruler_origin + V(vr_thickness + 3.0, 2.0, 0.0) # piotr 080326: moved the text origin to the cell center units_text_origin = ruler_origin + V(vr_thickness/2,hr_thickness/2,0.0) ruler_start_pt = ruler_origin \ + V(vr_thickness, hr_thickness, 0.0) origin_square_pt1 = V(width + vr_thickness, 0.0, 0.0) origin_square_pt2 = V(width, hr_thickness, 0.0) # VR vars. vr_rect_pt1 = V(width + vr_thickness, hr_thickness, 0.0) vr_rect_pt2 = V(width, height, 0.0) vr_line_pt1 = V(width + vr_thickness, 0.0, 0.0) vr_line_pt2 = V(width + vr_thickness, height, 0.0) vr_units_x_offset = 3.0 #@ Need way to right justify unit text! vr_units_y_offset = 3.0 vr_tickmark_spacing = tickmark_spacing # HR vars. hr_rect_pt1 = V(0.0, 0.0, 0.0) hr_rect_pt2 = V(width + vr_thickness, hr_thickness, 0.0) hr_line_pt1 = V(0.0, hr_thickness, 0.0) hr_line_pt2 = V(width, hr_thickness, 0.0) hr_long_tick_len *= -1.0 hr_medium_tick_len *= -1.0 hr_short_tick_len *= -1.0 hr_units_x_offset = -15.0 #@ Need way to right justify unit text! hr_units_y_offset = -hr_thickness * 0.8 hr_tickmark_spacing = -tickmark_spacing elif ruler_position == _upper_right: ruler_origin = V(width, height, 0.0) vr_thickness *= -1 # Note: Thickness is a negative value. hr_thickness *= -1 # Note: Thickness is a negative value. #units_text_origin = ruler_origin + V(vr_thickness * 0.8, # hr_thickness * 0.8, # 0.0) # piotr 080326: moved the text origin to the cell center units_text_origin = ruler_origin + V(hr_thickness/2,vr_thickness/2,0.0) ruler_start_pt = ruler_origin \ + V(vr_thickness, hr_thickness, 0.0) origin_square_pt1 = V(width + vr_thickness, height + hr_thickness, 0.0) origin_square_pt2 = V(width, height, 0.0) # VR vars. vr_rect_pt1 = V(width + vr_thickness, 0.0, 0.0) vr_rect_pt2 = V(width, height + hr_thickness, 0.0) vr_line_pt1 = V(width + vr_thickness, 0.0, 0.0) vr_line_pt2 = V(width + vr_thickness, height, 0.0) vr_units_x_offset = 3.0 #@ Need way to right justify unit text! vr_units_y_offset = -10.0 vr_tickmark_spacing = -tickmark_spacing # HR vars. hr_rect_pt1 = V(0.0, height + hr_thickness, 0.0) hr_rect_pt2 = V(width + vr_thickness, height, 0.0) hr_line_pt1 = V( 0.0, height + hr_thickness, 0.0) hr_line_pt2 = V(width, height + hr_thickness, 0.0) hr_units_x_offset = -15.0 #@ Need way to right justify unit text! hr_units_y_offset = -hr_thickness * 0.5 hr_tickmark_spacing = -tickmark_spacing else: msg = "bug: Illegal ruler position value (must be 0-3). Current "\ "value is %d. Ignoring." % ruler_position print_compact_stack(msg) return (draw_ticks_and_text, units_text, units_format, units_scale, unit_label_inc, long_tickmark_inc, medium_tickmark_inc, num_vert_ticks, num_horz_ticks, tickmark_spacing_multiplier, ruler_origin, ruler_start_pt, units_text_origin, origin_square_pt1, origin_square_pt2, vr_thickness, vr_tickmark_spacing, vr_long_tick_len, vr_medium_tick_len, vr_short_tick_len, vr_rect_pt1, vr_rect_pt2, vr_line_pt1, vr_line_pt2, vr_units_x_offset, vr_units_y_offset, hr_thickness, hr_tickmark_spacing, hr_long_tick_len, hr_medium_tick_len, hr_short_tick_len, hr_rect_pt1, hr_rect_pt2, hr_line_pt1, hr_line_pt2, hr_units_x_offset, hr_units_y_offset) class Guides(object): """ Creates a set of vertical and horizontal rulers in the 3D graphics area. A 2D window (pixel) coordinate system is created locally, where: - The lower left corner is ( 0.0, 0.0, 0.0) - The upper right corner is ( width, height, 0.0) This schematic shows the 2D window coodinate system with the rulers positioned in the lower left corner (their default position). (width, height) / +---+--------------------------------------+ | | | | v | | | e | | | r | | | t | | | i | | | c | | | a | ruler_start_pt | | l | (vr_thickness, hr_thickness, 0.0) | | |/ | +---+--------------------------------------+ | A | horizontal | +---+--------------------------------------+ / ruler_origin (0.0, 0.0, 0.0) It doesn't matter what coordinate system you are in when you call this function, and the system will not be harmed, but it does use one level on each matrix stack, and it does set matrixmode to GL_MODELVIEW before returning. Still to do: - Optimize. Don't call drawLine() multiple times; create a point list and render all tick marks at once. - Add support for 2D grid lines. - Allow user to control ruler thickness, ruler font size, tick mark color, etc via user preferences. (nice to have) - Center unit text in origin square (using QFontMetrics class to do this). (fixed by piotr 080326) @param glpane: the 3D graphics area. @type glpane: L{GLPane) @note: There is a pref key called I{displayRulers_prefs_key} that is set from the "View > Rulers" menu item. It is used in this function's sole caller (GLPane.standard_repaint_0()) to determine whether to draw any ruler(s). It is not used here. """ ruler_position = None scale = 0.0 zoomFactor = 0.0 aspect = 0.0 ruler_drawing_params = () if sys.platform == "darwin": # WARNING: Anything smaller than 9 pt on Mac OS X results in # un-rendered text. Not sure why. --Mark 2008-02-27 rulerFontPointSize = 9 else: rulerFontPointSize = 7 rulerFont = QFont( QString("Helvetica"), rulerFontPointSize) rulerFontMetrics = QFontMetrics(rulerFont) # piotr 080326 def __init__(self, glpane): """ Constructor for the guide objects (i.e. rulers). """ self.glpane = glpane def draw(self): """ Draws the rulers. """ width = self.glpane.width height = self.glpane.height # These 3 attrs (scale, aspect, and ruler_position) are checked to # determine if they've changed. If any of them have, # getRulerDrawingParameters() must be called to get new drawing parms. if (self.scale != self.glpane.scale) or \ (self.zoomFactor != self.glpane.zoomFactor) or \ (self.aspect != self.glpane.aspect) or \ (self.ruler_position != env.prefs[rulerPosition_prefs_key]): self.scale = self.glpane.scale self.zoomFactor = self.glpane.zoomFactor self.aspect = self.glpane.aspect self.ruler_position = env.prefs[rulerPosition_prefs_key] self.ruler_drawing_params = \ getRulerDrawingParameters(width, height, self.aspect, self.scale, self.zoomFactor, self.ruler_position) (draw_ticks_and_text, units_text, units_format, units_scale, unit_label_inc, long_tickmark_inc, medium_tickmark_inc, num_vert_ticks, num_horz_ticks, tickmark_spacing_multiplier, ruler_origin, ruler_start_pt, units_text_origin, origin_square_pt1, origin_square_pt2, vr_thickness, vr_tickmark_spacing, vr_long_tick_len, vr_medium_tick_len, vr_short_tick_len, vr_rect_pt1, vr_rect_pt2, vr_line_pt1, vr_line_pt2, vr_units_x_offset, vr_units_y_offset, hr_thickness, hr_tickmark_spacing, hr_long_tick_len, hr_medium_tick_len, hr_short_tick_len, hr_rect_pt1, hr_rect_pt2, hr_line_pt1, hr_line_pt2, hr_units_x_offset, hr_units_y_offset) = self.ruler_drawing_params ruler_color = env.prefs[rulerColor_prefs_key] ruler_opacity = env.prefs[rulerOpacity_prefs_key] # These may become user preferences in the future. tickmark_color = darkgray text_color = black # Set up 2D (window) coordinate system. # Bruce - please review this section. glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() # needed! gluOrtho2D(0.0, float(width), 0.0, float(height)) glMatrixMode(GL_MODELVIEW) # About this glMatrixMode(GL_MODELVIEW) call, Bruce wrote in a review: # The only reason this is desirable (it's not really needed) is if, # when someone is editing the large body of drawing code after this, # they inadvertently do something which is only correct if the matrix # mode is GL_MODELVIEW (e.g. if they use glTranslate to shift a ruler # or tickmark position). Most of our drawing code assumes it can do # this, so a typical NE1 OpenGL programmer may naturally assume this, # which is why it's good to leave the matrix mode as GL_MODELVIEW when # entering into a large hunk of ordinary drawing code (especially if # it might call other drawing functions, now or in the future). # Mark 2008-03-03 glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) # Note: disabling GL_DEPTH_TEST is not honored by the 3d version of # glpane.renderText -- ruler text can still be obscured by # previously drawn less-deep model objects. # But the 2d call of renderText in part.py does honor this. # The Qt doc says why, if I guess how to interpret it: # http://doc.trolltech.com/4.3/qglwidget.html#renderText # says, for the 3d version of renderText only (passing three model # coords as opposed to two window coords): # Note that this function only works properly if GL_DEPTH_TEST # is enabled, and you have a properly initialized depth buffer. # Possible fixes: # - revise ruler_origin to be very close to the screen, # and hope that this disable is merely ignored, not a messup; # - or, use the 2d version of the function. # I did the latter fix (2d renderText, below) and it seems to work. # [bruce 081204 comment] # Suppress writing into the depth buffer so anything behind the ruler # can still be highlighted/selected. glDepthMask(GL_FALSE) # == Draw v/h ruler rectangles in the user defined color and opacity. glColor4fv(list(ruler_color) + [ruler_opacity]) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glRectf(origin_square_pt1[0], origin_square_pt1[1], origin_square_pt2[0], origin_square_pt2[1]) # Origin square if env.prefs[displayVertRuler_prefs_key]: glRectf(vr_rect_pt1[0], vr_rect_pt1[1], vr_rect_pt2[0], vr_rect_pt2[1]) # Vertical ruler if env.prefs[displayHorzRuler_prefs_key]: glRectf(hr_rect_pt1[0], hr_rect_pt1[1], hr_rect_pt2[0], hr_rect_pt2[1]) # Horizontal ruler glDisable(GL_BLEND) # Set color of ruler lines, tick marks and text. glColor3fv(tickmark_color) self.glpane.qglColor(RGBf_to_QColor(text_color)) # Draw unit of measurement in corner (A or nm). # piotr 080326: replaced drawText with drawCenteredText self.drawCenteredText(units_text, units_text_origin) # Kludge alert. Finish drawing ruler edge(s) if we will not be # drawing the ruler tick marks and text (only happens when the user # is zoomed out to an "absurd scale factor"). if not draw_ticks_and_text: if env.prefs[displayVertRuler_prefs_key]: self.drawLine(vr_line_pt1, vr_line_pt2) if env.prefs[displayHorzRuler_prefs_key]: self.drawLine(hr_line_pt1, hr_line_pt2) # == Draw vertical ruler line(s) and tick marks if env.prefs[displayVertRuler_prefs_key] and draw_ticks_and_text: # Draw vertical line along right/left edge of ruler. self.drawLine(vr_line_pt1, vr_line_pt2) # Initialize pt1 and pt2, the tick mark endpoints. The first tick # mark will span the entire width of the ruler, which serves as a # divider b/w the unit of measure text (i.e. A or nm) and the rest # of the ruler. pt1 = ruler_start_pt pt2 = ruler_start_pt + V(-vr_thickness, 0.0, 0.0) # Draw vertical ruler tickmarks, including numeric unit labels for tick_num in range(num_horz_ticks + 1): # pt1 and pt2 are modified by each iteration of the loop. self.drawLine(pt1, pt2) # Draw units number beside long tickmarks. if not tick_num % unit_label_inc: units_num_origin = pt1 \ + V(vr_units_x_offset, vr_units_y_offset, 0.0) units_num = units_format % (tick_num * units_scale) self.drawText(units_num, units_num_origin) # Update tickmark endpoints for next tickmark. pt1 = ruler_start_pt + \ V(0.0, vr_tickmark_spacing * tickmark_spacing_multiplier * (tick_num + 1), 0.0) if not (tick_num + 1) % long_tickmark_inc: pt2 = pt1 + V(vr_long_tick_len, 0.0, 0.0) elif not (tick_num + 1) % medium_tickmark_inc: pt2 = pt1 + V(vr_medium_tick_len, 0.0, 0.0) else: pt2 = pt1 + V(vr_short_tick_len, 0.0, 0.0) # End vertical ruler # == Draw horizontal ruler line(s) and tick marks if env.prefs[displayHorzRuler_prefs_key] and draw_ticks_and_text: # Draw horizontal line along top/bottom edge of ruler. self.drawLine(hr_line_pt1, hr_line_pt2) # Initialize pt1 and pt2, the tick mark endpoints. The first tick # mark will span the entire width of the ruler, which serves as a # divider b/w the unit of measure text (i.e. A or nm) and the rest # of the ruler. pt1 = ruler_start_pt pt2 = ruler_start_pt + V(0.0, -hr_thickness, 0.0) # Draw horizontal ruler (with vertical) tickmarks, including its # numeric unit labels for tick_num in range(num_vert_ticks + 1): # pt1 and pt2 are modified by each iteration of the loop. self.drawLine(pt1, pt2) # Draw units number beside long tickmarks. if not tick_num % unit_label_inc: units_num_origin = pt1 \ + V(hr_units_x_offset, hr_units_y_offset, 0.0) units_num = units_format % (tick_num * units_scale) self.drawText(units_num, units_num_origin) # Update tickmark endpoints for next tickmark. pt1 = \ ruler_start_pt + \ V(hr_tickmark_spacing * tickmark_spacing_multiplier * (tick_num + 1), 0.0, 0.0) if not (tick_num + 1) % long_tickmark_inc: pt2 = pt1 + V(0.0, hr_long_tick_len, 0.0) elif not (tick_num + 1) % medium_tickmark_inc: pt2 = pt1 + V(0.0, hr_medium_tick_len, 0.0) else: pt2 = pt1 + V(0.0, hr_short_tick_len, 0.0) # End horizontal ruler # Restore OpenGL state. glDepthMask(GL_TRUE) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glDepthMask(GL_TRUE) glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() return # from drawRulers def drawLine(self, pt1, pt2): """ Draws ruler lines that are 1 pixel wide. """ if 0: # Used for debugging. return glBegin(GL_LINES) glVertex(pt1[0], pt1[1], pt1[2]) glVertex(pt2[0], pt2[1], pt2[2]) glEnd() return def drawText(self, text, origin): """ Draws ruler text. """ # WARNING: if we want to optimize by putting the ruler into an OpenGL display list, # this might not work anymore, since renderText seems to not work in display lists # when used for drawing bond letters in bond_drawer.py. [bruce 081204 comment] if not text: return self.glpane.renderText( ## origin[0], origin[1], origin[2], # model coordinates origin[0], self.glpane.height - origin[1], # window coordinates # using 2d window coordinates fixes the bug in which this text # is obscured by model objects which should be behind it. # For explanation, see comment near GL_DEPTH_TEST above. # [bruce 081204 bugfix] QString(text), self.rulerFont ) return def drawCenteredText(self, text, origin): """ Draws ruler text centered, so text center == origin. """ # added by piotr 080326 if not text: return fm = self.rulerFontMetrics # get the text dimensions in world coordinates x0, y0, z0 = gluUnProject(0,0,0) x1, y1, z1 = gluUnProject(fm.width(text),fm.ascent(),0) # compute a new origin relative to the old one new_origin = origin - 0.5 * V(x1-x0, y1-y0, z1-z0) # render the text self.drawText( text, new_origin) return
NanoCAD-master
cad/src/graphics/drawing/Guides.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ texture_helpers.py -- helper functions for using OpenGL textures @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. """ from OpenGL.GL import glGenTextures from OpenGL.GL import GL_TEXTURE_2D from OpenGL.GL import glBindTexture from OpenGL.GL import GL_UNPACK_ALIGNMENT from OpenGL.GL import glPixelStorei from OpenGL.GL import GL_RGBA from OpenGL.GL import GL_UNSIGNED_BYTE from OpenGL.GL import glTexImage2D from OpenGL.GL import GL_CLAMP from OpenGL.GL import GL_TEXTURE_WRAP_S from OpenGL.GL import glTexParameterf from OpenGL.GL import GL_TEXTURE_WRAP_T from OpenGL.GL import GL_REPEAT from OpenGL.GL import GL_LINEAR from OpenGL.GL import GL_TEXTURE_MAG_FILTER from OpenGL.GL import GL_LINEAR_MIPMAP_LINEAR from OpenGL.GL import GL_TEXTURE_MIN_FILTER from OpenGL.GL import GL_NEAREST from OpenGL.GL import GL_DECAL from OpenGL.GL import GL_TEXTURE_ENV from OpenGL.GL import GL_TEXTURE_ENV_MODE from OpenGL.GL import glTexEnvf from OpenGL.GLU import gluBuild2DMipmaps from utilities.debug_prefs import Choice_boolean_False # in disabled code from utilities.debug_prefs import debug_pref # in disabled code # note this runtime import below -- TODO, find out if it can be toplevel; # the file it imports is not now [071017] in any import cycles: ## from ImageUtils import nEImageOps # == # higher-level helpers def load_image_into_new_texture_name(image_file, tex_name = 0): """ Allocate texture object in current GL Context (or use given one) (either way, return have_mipmaps, tex_name) and load image from file into it. [what if wrong size??] """ # took code from ESPImage image_obj = create_PIL_image_obj_from_image_file( image_file) have_mipmaps, tex_name = loadTexture(image_obj, tex_name) return have_mipmaps, tex_name # TODO: rename, docstring def setup_to_draw_texture_name(have_mipmaps, tex_name): """ #doc Anything that calls this should eventually call glpane.kluge_reset_texture_mode_to_work_around_renderText_bug(), but only after all drawing using the texture is done. """ # assume it's already set up [what does that mean? bruce 071017] #e bind it glBindTexture(GL_TEXTURE_2D, tex_name) _initTextureEnv(have_mipmaps) # sets texture params the way we want them ## now you can: (from ESPImage._draw_jig, which before this did pushmatrix ## etc) ## drawPlane(self.fill_color, self.width, self.width, textureReady, ## self.opacity, SOLID = True, pickCheckOnly = False) ##hw = self.width/2.0 ##corners_pos = [V(-hw, hw, 0.0), V(-hw, -hw, 0.0), ## V(hw, -hw, 0.0), V(hw, hw, 0.0)] ##drawLineLoop(color, corners_pos) return # == # lower-level helpers modified from ESPImage # [note: some of these are called from exprs/images.py; others are copied & # modified into it [bruce 061125]] # misnamed, see docstring; added kws, 061127 def create_PIL_image_obj_from_image_file(image_file, **kws): ### TODO: refile this into ImageUtils? """ Creates and returns an nEImageOps object (using the given kws, documented in ImageUtils.py), which contains (and sometimes modifies in place) a PIL image object made from the named image file. """ from graphics.images.ImageUtils import nEImageOps return nEImageOps(image_file, **kws) def loadTexture(image_obj, tex_name = 0): #e arg want_mipmaps """ Load texture data from current image object; return have_mipmaps, tex_name (also leave that texture bound, BTW) """ # note: some of this code has been copied into exprs/images.py, class # texture_holder [bruce 061125] ix, iy, image = image_obj.getTextureData() # allocate texture object if necessary if not tex_name: tex_name = glGenTextures(1) # It's deprecated to let this happen much. [070308] print "debug fyi: texture_helpers.loadTexture allocated tex_name %r" %\ (tex_name,) # note: by experiment (iMac G5 Panther), this returns a single number # (1L, 2L, ...), not a list or tuple, but for an argument >1 it returns # a list of longs. We depend on this behavior here. [bruce 060207] tex_name = int(tex_name) # make sure it worked as expected assert tex_name != 0 # initialize texture data glBindTexture(GL_TEXTURE_2D, tex_name) # 2d texture (x and y size) glPixelStorei(GL_UNPACK_ALIGNMENT,1) ###k what's this? have_mipmaps = False ##want_mipmaps = debug_pref("smoother tiny textures", ## Choice_boolean_False, prefs_key = True) want_mipmaps = True if want_mipmaps: gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, ix, iy, GL_RGBA, GL_UNSIGNED_BYTE, image) have_mipmaps = True else: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) # 0 is mipmap level, GL_RGBA is internal format, ix, iy is size, 0 # is borderwidth, and (GL_RGBA, GL_UNSIGNED_BYTE, image) describe # the external image data. [bruce 060212 comment] return have_mipmaps, tex_name # This gets us ready to draw (using coords in) a texture if we have it bound, I # think. Called during draw method [modified from ESPImage.] #e need smooth = False/True def _initTextureEnv(have_mipmaps): """ have_mipmaps is boolean #doc Anything that calls this should eventually call glpane.kluge_reset_texture_mode_to_work_around_renderText_bug(), but only after all drawing using the texture is done. """ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) # [looks like a bug that we overwrite clamp with repeat, just below? # bruce 060212 comment] glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) if (0 and "kluge" and debug_pref("smoother textures", Choice_boolean_False, prefs_key = True)): ###@@@ revise to param #bruce 060212 new feature (only visible in debug version so far); # ideally it'd be controllable per-jig for side-by-side comparison; # also, changing its menu item ought to gl_update but doesn't ##e glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) if have_mipmaps: ###@@@ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) else: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) return # end
NanoCAD-master
cad/src/graphics/drawing/texture_helpers.py
# Copyright 2009 Nanorex, Inc. See LICENSE file for details. """ DrawingSetCache.py -- cache of DrawingSets with associated drawing intents @author: Bruce @version: $Id$ @copyright: 2009 Nanorex, Inc. See LICENSE file for details. History: Bruce 090313 moved into its own file, from GLPane_drawingset_methods.py, then factored a lot of access/modification code from its client code remaining in that file into new methods in this class. TODO: add usage tracking. """ import foundation.env as env # soon: from foundation.changes import SelfUsageTrackingMixin, SubUsageTrackingMixin from graphics.drawing.DrawingSet import DrawingSet # == class DrawingSetCache(object, # soon: SelfUsageTrackingMixin, SubUsageTrackingMixin #bruce 090313 ): #bruce 090227 """ A persistent cache of DrawingSets, one for each "drawing intent" specified in the input passed to self.incrementally_set_contents_to(). (As we're presently used by GLPane_drawingset_methods, that's the same set of intents as are passed to glpane.draw_csdl.) Some attributes and methods are public. """ # default values of instance variables saved_change_indicator = None #bruce 090309 # public for set and compare (by '==') def __init__(self, cachename, temporary): self.cachename = cachename # (public, but not used externally [as of 090313]) self.temporary = temporary # (public, not used *internally* [as of 090313]) self._dsets = {} # maps drawing intent to DrawingSet; # presently private re access/modification, # and so are the dsets it contains return def destroy(self): for dset in self._dsets.values(): dset.destroy() self._dsets = {} self.saved_change_indicator = None return def incrementally_set_contents_to(self, intent_to_csdls, ## dset_change_indicator = None ): """ Incrementally modify our DrawingSets (creating or destroying some of them, modifying others) so that their content matches that of the provided dict, intent_to_csdls, which we take ownership of and are allowed to arbitrarily modify. @param intent_to_csdls: a dict from drawing intents (about how a csdl's drawingset should be drawn -- we need to put each csdl into a dset which will be drawn in the way it intends) to dicts of CSDLs (which maps csdl.csdl_id to csdl). We are allowed to arbitrarily modify this dict, so caller should not use it after passing it to us. ## @param dset_change_indicator: if provided (and not false), ## save this as the value of self.saved_change_indicator. """ #bruce 090313 factored this method out of our client code ## if dset_change_indicator: ## self.saved_change_indicator = dset_change_indicator ## ##### REVIEW: if not, save None? dsets = self._dsets # review: consider refactoring to turn code around all uses of this # into methods in DrawingSetCache # 1. handle existing dsets/intents in self # (note: if client uses us non-incrementally, we are initially empty, # so this step efficiently does nothing) # # - if any prior DrawingSets are completely unused, get rid of them # (note: this defeats future optimizations based on intents which are # "turned on and off", such as per-Part or per-graphicsMode # intents; we'll need to rethink something if we want those here) # # - for the other prior DrawingSets, figure out csdls to remove and # add; try to optimize for no change; try to do removals first, # to save RAM in case cache updates during add are immediate for intent, dset in dsets.items(): # not iteritems! if intent not in intent_to_csdls: # this intent is not needed at all for this frame dset.destroy() del dsets[intent] else: # this intent is used this frame; update dset.CSDLs # (using a method which optimizes that into the # minimal number of inlined removes and adds) csdls_wanted = intent_to_csdls.pop(intent) dset.set_CSDLs( csdls_wanted) del csdls_wanted # junk now, since set_CSDLs owns it continue # 2. handle new intents (if we were initially non-empty, i.e. being used # incrementally) or all intents (when used non-incrementally): # make new DrawingSets for whatever intents remain in intent_to_csdls for intent, csdls in intent_to_csdls.items(): del intent_to_csdls[intent] # (this might save temporary ram, depending on python optims) dset = DrawingSet(csdls.itervalues()) dsets[intent] = dset # always store them here; remove them later if non-incremental del intent, csdls, dset # notice bug of reusing these below (it happened, when this was inlined into caller) continue return def draw(self, glpane, intent_to_options_func, debug = False, destroy_as_drawn = False ): """ Draw all our DrawingSets (in glpane) with appropriate options based on their drawing intents, as determined by intent_to_options_func. @param debug: if true, print debugging info. """ if debug: print print env.redraw_counter , print " cache %r%s" % (self.cachename, self.temporary and " (temporary)" or "") , print " (for phase %r)" % glpane.drawing_phase pass for intent, dset in self._dsets.items(): if debug: print "drawing dset, intent %r, %d items" % \ (intent, len(dset.CSDLs), ) pass options = intent_to_options_func(intent) dset.draw(**options) if destroy_as_drawn: # don't save them any longer than needed, to save RAM # (without this, we'd destroy them all at once near start # of next frame, using code above our call in client, # or later in this frame) dset.destroy() del self._dsets[intent] continue return pass # end of class DrawingSetCache # end
NanoCAD-master
cad/src/graphics/drawing/DrawingSetCache.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ drawing_globals.py - A module containing global state within the graphics.drawing suite (which is, in principle, mostly specific to one "GL resource context" (display list namespace, etc)). For historical reasons, a lot of its state is assigned from outside, and some of it is not in principle specific to a resource context but is either a constant or ought to be part of an argument passed to drawing routines. @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. WARNINGS: Variables can be (and are) dynamically added to this module at runtime. Note: Setting globals here should not be (but, unfortunately, is presently) done as a side effect of loading other modules. It makes the imports of those modules falsely appear unnecessary, since nothing defined in them is used. It also confuses tools which import the module in which the assignment is used, but not the one which makes the assignment. Some of the variables contained here are mode control for the whole drawing package, including the ColorSorter suite. Other parts are communication between the phases of setup and operations, which is only incidentally about OpenGL. Other things are just geometric constants useful for setting up display lists, e.g. a list of vertices of a diamond grid. Usage: Import it this way to show that it is a module: import graphics.drawing.drawing_globals as drawing_globals Access variables as drawing_globals.varname . TODO: Desireable refactoring: Note that most of this state really belongs in an object that corresponds to each "GL display list namespace" aka "GL resource context", i.e. each OpenGL shared resource pool of display lists, textures, shaders, VBOs, etc. In current code, we require all OpenGL drawing contexts to share that state, so we can get away with keeping it as globals in a module. Even so, this ought to be refactored, since this way it makes the code less clear, causes import cycles and dependencies on import order, confuses pylint, etc. (Bruce 090303 is doing related cleanup by introducing ShaderGlobals and moving shader prefs into GLPrefs, but the fundamental change is still needed.) """ from graphics.drawing.glprefs import GLPrefs # more imports are kept below, since they will be refactored into a separate module # == # A singleton instance of the GLPrefs class. # This is used in only these ways: # - by old code (perhaps all being refactored away circa 090304) # - to initialize glpane.glprefs when there is no other source. # It must be initialized during import of this module, # or some code would risk importing a value for it from before # it was initialized. # If this causes an import cycle, it can be moved to another module, # since it's not otherwise used in this module. # [review: rename it to avoid confusion, once all old uses are removed?] glprefs = GLPrefs() # ===== # these are assigned by external code (incomplete list; # defined here to partly mollify pylint; not yet classified # into how to distribute them after refactoring; to find lots more, # use pylint on various modules in graphics/drawing) drawing_phase = None # ===== # Everything below here should be something that belongs in an object # that corresponds to a "GL resource context"' someday we will refactor # this module into such an object (owned by each glpane) and other things. # For example, fixed-use OpenGL display lists (like sphereList) belong here. # (Presently many such things are stored here by external code, like setup_draw. # That should be changed too.) # [bruce 090304] from graphics.drawing.ShaderGlobals import SphereShaderGlobals from graphics.drawing.ShaderGlobals import CylinderShaderGlobals sphereShaderGlobals = SphereShaderGlobals() cylinderShaderGlobals = CylinderShaderGlobals() # for use by test_drawing.py only, shares no state with other globals test_sphereShader = None # == def setup_desired_shaders(glprefs): #bruce 090303 """ Setup shaders within our state, according to shader-use desires of glprefs. @note: does not check glpane.permit_shaders. """ if glprefs.sphereShader_desired(): sphereShaderGlobals.setup_if_needed_and_not_failed() if glprefs.cylinderShader_desired(): cylinderShaderGlobals.setup_if_needed_and_not_failed() return def sphereShader_available(): #bruce 090306 return sphereShaderGlobals.shader_available() def cylinderShader_available(): return cylinderShaderGlobals.shader_available() coneShader_available = cylinderShader_available # == def enabled_shaders(glpane): #bruce 090303 """ Return a list of the shaders that are enabled for use during this drawing frame (in a deterministic order), in this glpane. "enabled" means three things are true: * desired for its types of primitives in CSDLs (re glpane.glprefs), * available for use (re shader setup errors; see shader_available), * permitted for use (glpane.permit_shaders). @note: the result is currently [090303] one of the values [] [sphereShader] [cylinderShader] [sphereShader, cylinderShader] where sphereShader and cylinderShader are instances of subclasses of GLShaderObject which are enabled for current use in the GL resource context represented by this (singleton) module. Note that prefs might request a shader without it being enabled (due to error or to its not yet being created), or it might exist and be useable without prefs wanting to use it (if they were turned off during the session). """ glprefs = glpane.glprefs res = [] if glpane.permit_shaders and glprefs._use_batched_primitive_shaders: # note: testing _use_batched_primitive_shaders is just # an optimization (and a kluge) (so nevermind that it's private) for desired, shaderGlobals in [ (glprefs.sphereShader_desired(), sphereShaderGlobals), (glprefs.cylinderShader_desired(), cylinderShaderGlobals), ]: if desired and shaderGlobals.shader_available(): res += [ shaderGlobals.shader ] continue return res # end
NanoCAD-master
cad/src/graphics/drawing/drawing_globals.py
# Copyright 2007-2009 Nanorex, Inc. See LICENSE file for details. """ Draws the DNA ribbons where each strand is represented as a ribbon. DNA ribbons are drawn as sine waves @author: Ninad @copyright: 2007-2009 Nanorex, Inc. See LICENSE file for details. @version: $Id$ @license: GPL TODO: It should support various display styles that match with the display of the actual model. """ import foundation.env as env from math import asin, acos from Numeric import sin, cos, pi ONE_RADIAN = 180.0 / pi HALF_PI = pi/2.0 TWICE_PI = 2*pi from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushMatrix from OpenGL.GL import glTranslatef from graphics.drawing.drawers import drawArrowHead from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.drawers import drawPoint from graphics.drawing.CS_draw_primitives import drawsphere from graphics.drawing.drawers import drawtext from geometry.VQT import norm, vlen, V, cross, Q from geometry.VQT import orthodist, angleBetween from utilities.constants import white, blue from utilities.constants import diTrueCPK, diTUBES, diLINES from Numeric import dot from utilities.prefs_constants import DarkBackgroundContrastColor_prefs_key #Constants for drawing the ribbon points as spheres. SPHERE_RADIUS = 1.0 SPHERE_DRAWLEVEL = 2 SPHERE_OPACITY = 1.0 #Constants for drawing the second axis end point (as a sphere). AXIS_ENDPOINT_SPHERE_COLOR = white AXIS_ENDPOINT_SPHERE_RADIUS = 1.0 AXIS_ENDPOINT_SPHERE_DRAWLEVEL = 2 AXIS_ENDPOINT_SPHERE_OPACITY = 0.5 def draw_debug_text(glpane, point, text): #bruce 080422, should refile """ """ from geometry.VQT import V from utilities.constants import white, red if point is None: point = - glpane.pov # todo: randomize offset using hash of text offset = glpane.right * glpane.scale / 2.0 + \ glpane.up * glpane.scale / 2.0 # todo: correct for aspect ratio, use min scale in each dimension offset2 = V( - offset[0], offset[1], 0.0 ) / 3.0 drawline( white, point, point + offset, width = 2) drawline( white, point - offset2, point + offset2 ) point_size = 12 drawtext( text, red, point + offset, point_size, glpane ) return # This needs to include axial offset from caller. def _compute_ribbon_point(origin, basesPerTurn, duplexRise, unitVectorAlongLength, unitVectorAlongLadderStep, unitDepthVector, peakDeviationFromCenter, numberOfBasesDrawn , theta_offset ): """ """ ##handedness = -1 ##theta_offset = 0.0 #turn_angle = twistPerBase ##turn_angle = (handedness * 2 * pi) / basesPerTurn turn_angle = (2 * pi) / basesPerTurn ## axial_offset = unitVectorAlongLength * duplexRise cY = unitVectorAlongLadderStep cZ = unitDepthVector theta = turn_angle * numberOfBasesDrawn + theta_offset # in radians y = cos(theta) * peakDeviationFromCenter z = sin(theta) * peakDeviationFromCenter ## vx = axial_offset # a Vector p = origin + y * cY + z * cZ return p def drawDnaSingleRibbon(glpane, endCenter1, endCenter2, basesPerTurn, duplexRise, # maybe: don't pass these three args, get from glpane # instead? [bruce 080422 comment] glpaneScale, lineOfSightVector, displayStyle, ribbon1_start_point = None, ribbon1_direction = None, peakDeviationFromCenter = 9.5, ribbonThickness = 2.0, ribbon1Color = None, stepColor = None): """ @see: drawDnaRibbons (method in this file) @see: DnaStrand_GraphicsMode._drawHandles() """ if 0: # debug code, useful to see where the argument points are located # [bruce 080422] draw_debug_text(glpane, endCenter1, "endCenter1") draw_debug_text(glpane, endCenter2, "endCenter2") draw_debug_text(glpane, ribbon1_start_point, "ribbon1_start_point") #Try to match the rubberband display style as closely as possible to #either the glpane's current display or the chunk display of the segment #being edited. The caller should do the job of specifying the display style #it desires. As of 2008-02-20, this method only supports following display #styles --Tubes, Ball and Stick, CPK and lines. the sphere radius #for ball and stick or CPK is calculated approximately. if displayStyle == diTrueCPK: SPHERE_RADIUS = 3.5 ribbonThickness = 2.0 elif displayStyle == diTUBES: SPHERE_RADIUS = 0.01 ribbonThickness = 5.0 elif displayStyle == diLINES: #Lines display and all other unsupported display styles SPHERE_RADIUS = 0.01 ribbonThickness = 1.0 else: #ball and stick display style. All other unsupported displays #will be rendered in ball and stick display style SPHERE_RADIUS = 1.0 ribbonThickness = 3.0 if stepColor is None: stepColor = env.prefs[DarkBackgroundContrastColor_prefs_key] ribbonLength = vlen(endCenter1 - endCenter2) #Don't draw the vertical line (step) passing through the startpoint unless #the ribbonLength is at least equal to the duplexRise. # i.e. do the drawing only when there are at least two ladder steps. # This prevents a 'revolving line' effect due to the single ladder step at # the first endpoint. It also means the dna duplex axis can be determined # below from the two endpoints. if ribbonLength < duplexRise: return unitVectorAlongLength = norm(endCenter2 - endCenter1) glDisable(GL_LIGHTING) ##glPushMatrix() ##glTranslatef(endCenter1[0], endCenter1[1], endCenter1[2]) ##pointOnAxis = V(0, 0, 0) pointOnAxis = endCenter1 axial_shift = V(0.0, 0.0, 0.0) # might be changed below # [these might be discarded and recomputed just below; # the case where they aren't is (and I think was) untested. # -- bruce 080422 comment] vectorAlongLadderStep = cross(-lineOfSightVector, unitVectorAlongLength) unitVectorAlongLadderStep = norm(vectorAlongLadderStep) unitDepthVector = cross(unitVectorAlongLength, unitVectorAlongLadderStep) ## * -1 if ribbon1_start_point is not None: # [revise the meaning of these values to give the coordinate system # with the right phase in which to draw the ribbon. # bruce 080422 bugfix] vectorAlongLadderStep0 = ribbon1_start_point - endCenter1 # note: this might not be perpendicular to duplex axis. # fix by subtracting off the parallel component. # but add the difference back to every point below. vectorAlongLadderStep = vectorAlongLadderStep0 - \ dot( unitVectorAlongLength, vectorAlongLadderStep0 ) * unitVectorAlongLength axial_shift = (vectorAlongLadderStep0 - vectorAlongLadderStep) # note: even using this, there is still a small glitch in the # location of the first drawn sphere vs. the ribbon point... don't # know why. [bruce 080422] unitVectorAlongLadderStep = norm(vectorAlongLadderStep) unitDepthVector = cross(unitVectorAlongLength, unitVectorAlongLadderStep) ## * -1 pass del vectorAlongLadderStep ###=== #Following limits the arrowHead Size to the given value. When you zoom out, #the rest of ladder drawing becomes smaller (expected) and the following #check ensures that the arrowheads are drawn proportionately. # (Not using a 'constant' to do this as using glpaneScale gives better #results) if glpaneScale > 40: arrowDrawingScale = 40 else: arrowDrawingScale = glpaneScale #Formula .. Its a Sine Wave. # y(x) = A.sin(2*pi*f*x + phase_angle) ------[1] # where -- # f = 1/T # A = Amplitude of the sine wave (or 'peak deviation from center') # y = y coordinate of the sine wave -- distance is in Angstroms # x = the x coordinate # phase_angle is computed for each wave. We know y at x =0. For example, # for ribbon_1, , at x = 0, y = A. Putting these values in equation [1] # we get the phase_angle. x = 0.0 T = duplexRise * basesPerTurn # The 'Period' of the sine wave # (i.e. peak to peak distance between consecutive crests) numberOfBasesDrawn = 0 theta_offset = 0 ## phase_angle_ribbon_1 = HALF_PI ## theta_ribbon_1 = (TWICE_PI * x / T) + phase_angle_ribbon_1 #Initialize ribbon1_point # [note: might not be needed, since identical to first point # computed during loop, but present code uses it to initialize # previous_ribbon1_point during loop [bruce 080422 comment]] ribbon1_point = _compute_ribbon_point(pointOnAxis + axial_shift, basesPerTurn, duplexRise, unitVectorAlongLength, unitVectorAlongLadderStep, unitDepthVector, peakDeviationFromCenter, numberOfBasesDrawn, theta_offset ) while x < ribbonLength: #Draw the axis point. drawPoint(stepColor, pointOnAxis) previousPointOnAxis = pointOnAxis previous_ribbon1_point = ribbon1_point ribbon1_point = _compute_ribbon_point(pointOnAxis + axial_shift, basesPerTurn, duplexRise, unitVectorAlongLength, unitVectorAlongLadderStep, unitDepthVector, peakDeviationFromCenter, numberOfBasesDrawn, theta_offset ) if x == duplexRise and ribbon1_direction == -1: # For ribbon_2 we need to draw an arrow head for y at x = 0. # To do this, we need the 'next ribbon_2' point in order to # compute the appropriate vectors. So when x = duplexRise, the # previous_ribbon2_point is nothing but y at x = 0. arrowLengthVector2 = norm(ribbon1_point - previous_ribbon1_point ) arrowHeightVector2 = cross(-lineOfSightVector, arrowLengthVector2) drawArrowHead( ribbon1Color, previous_ribbon1_point, arrowDrawingScale, -arrowHeightVector2, -arrowLengthVector2) # Draw sphere over previous_ribbon1_point and not ribbon1_point. # This is so we don't draw a sphere over the last point on ribbon1 # (instead, it is drawn as an arrowhead after the while loop). drawsphere(ribbon1Color, previous_ribbon1_point, SPHERE_RADIUS, SPHERE_DRAWLEVEL, opacity = SPHERE_OPACITY) drawline(stepColor, pointOnAxis, ribbon1_point) #Increment the pointOnAxis and x pointOnAxis = pointOnAxis + unitVectorAlongLength * duplexRise x += duplexRise numberOfBasesDrawn += 1 if previous_ribbon1_point: drawline(ribbon1Color, previous_ribbon1_point, ribbon1_point, width = ribbonThickness, isSmooth = True ) arrowLengthVector1 = norm(ribbon1_point - previous_ribbon1_point) arrowHeightVector1 = cross(-lineOfSightVector, arrowLengthVector1) pass continue # while x < ribbonLength if ribbon1_direction == 1: #Arrow head for endpoint of ribbon_1. drawArrowHead(ribbon1Color, ribbon1_point, arrowDrawingScale, arrowHeightVector1, arrowLengthVector1) #The second axis endpoint of the dna is drawn as a transparent sphere. #Note that the second axis endpoint is NOT NECESSARILY endCenter2 . In fact # those two are equal only at the ladder steps. In other case (when the # ladder step is not completed), the endCenter1 is ahead of the #'second axis endpoint of the dna' drawsphere(AXIS_ENDPOINT_SPHERE_COLOR, previousPointOnAxis, AXIS_ENDPOINT_SPHERE_RADIUS, AXIS_ENDPOINT_SPHERE_DRAWLEVEL, opacity = AXIS_ENDPOINT_SPHERE_OPACITY) ##glPopMatrix() glEnable(GL_LIGHTING) return # from drawDnaSingleRibbon def drawDnaRibbons(glpane, endCenter1, endCenter2, basesPerTurn, duplexRise, glpaneScale, lineOfSightVector, displayStyle, ribbon1_start_point = None, ribbon2_start_point = None, ribbon1_direction = None, ribbon2_direction = None, peakDeviationFromCenter = 9.5, ribbonThickness = 2.0, ribbon1Color = None, ribbon2Color = None, stepColor = None): """ Draw DNA ribbons where each strand is represented as a ribbon. DNA ribbons are drawn as sine waves with appropriate phase angles, with the phase angles computed in this method. @param endCenter1: Axis end 1 @type endCenter1: B{V} @param endCenter2: Axis end 2 @type endCenter2: B{V} @param basesPerTurn: Number of bases in a full turn. @type basesPerTurn: float @param duplexRise: Center to center distance between consecutive steps @type duplexRise: float @param glpaneScale: GLPane scale used in scaling arrow head drawing @type glpaneScale: float @param lineOfSightVector: Glpane lineOfSight vector, used to compute the the vector along the ladder step. @type: B{V} @param displayStyle: Rubberband display style (specified as an integer) see comment in the method below. See also GLPane.displayMode. @type displayStyle: int @param peakDeviationFromCenter: Distance of a peak from the axis Also known as 'Amplitude' of a sine wave. @type peakDeviationFromCenter: float @param ribbonThickness: Thickness of each of the the two ribbons @type ribbonThickness: float @param ribbon1Color: Color of ribbon1 @param ribbon2Color: Color of ribbon2 @see: B{DnaLineMode.Draw } (where it is used) for comments on color convention TODO: as of 2008-04-22 - Need more documentation - This method is long mainly because of a number of custom drawing See if that can be refactored e.g. methods like _drawRibbon1/strand1, drawRibbon2 / strand2 etc. - Further optimization / refactoring (low priority) """ #Try to match the rubberband display style as closely as possible to #either the glpane's current display or the chunk display of the segment #being edited. The caller should do the job of specifying the display style #it desires. As of 2008-02-20, this method only supports following display #styles --Tubes, Ball and Stick, CPK and lines. the sphere radius #for ball and stick or CPK is calculated approximately. if displayStyle == diTrueCPK: SPHERE_RADIUS = 3.5 ribbonThickness = 2.0 elif displayStyle == diTUBES: SPHERE_RADIUS = 0.01 ribbonThickness = 5.0 elif displayStyle == diLINES: #Lines display and all other unsupported display styles SPHERE_RADIUS = 0.01 ribbonThickness = 1.0 else: #ball and stick display style. All other unsupported displays #will be rendered in ball and stick display style SPHERE_RADIUS = 1.0 ribbonThickness = 3.0 ribbonLength = vlen(endCenter1 - endCenter2) #Don't draw the vertical line (step) passing through the startpoint unless #the ribbonLength is at least equal to the duplexRise. # i.e. do the drawing only when there are at least two ladder steps. # This prevents a 'revolving line' effect due to the single ladder step at # the first endpoint if ribbonLength < duplexRise: return unitVectorAlongLength = norm(endCenter2 - endCenter1) ###=== pointOnAxis = endCenter1 axial_shift_1 = V(0.0, 0.0, 0.0) # might be changed below axial_shift_2 = V(0.0, 0.0, 0.0) # [these might be discarded and recomputed just below; # the case where they aren't is (and I think was) untested. # -- bruce 080422 comment] vectorAlongLadderStep = cross(-lineOfSightVector, unitVectorAlongLength) unitVectorAlongLadderStep = norm(vectorAlongLadderStep) unitDepthVector = cross(unitVectorAlongLength, unitVectorAlongLadderStep) ## * -1 numberOfBasesDrawn = 0 theta_offset = 0 x = 0 ### #Formula .. Its a Sine Wave. # y(x) = A.sin(2*pi*f*x + phase_angle) ------[1] # where -- # f = 1/T # A = Amplitude of the sine wave (or 'peak deviation from center') # y = y coordinate of the sine wave -- distance is in Angstroms # x = the x coordinate # phase_angle is computed for each wave. We know y at x =0. For example, # for ribbon_1, , at x = 0, y = A. Putting these values in equation [1] # we get the phase_angle. Similarly, for ribbon_2, at x = 0, y = -6 # Putting these values will give use the phase_angle_2. # Note that for ribbon2_point, we subtract the value of equation [1] from # the point on axis. x = 0.0 T = duplexRise * basesPerTurn # The 'Period' of the sine wave # (i.e. peak to peak distance between consecutive crests) amplitude = peakDeviationFromCenter amplitudeVector = unitVectorAlongLadderStep * amplitude depthVector = unitDepthVector * amplitude # Note: to reduce the effect of perspective view on rung direction, # we could multiply depthVector by 0.1 or 0.01. But this would lessen # the depth realism of line/sphere intersections. [bruce 080216] ### if ribbon1_start_point is not None: ribbon1_point = ribbon1_start_point else: if ribbon2_start_point is not None: ribbon1_point = _get_ribbon_point_on_other_ribbon( ribbon2_start_point, ribbon2_direction, endCenter1, unitVectorAlongLength) else: phase_angle_ribbon_1 = HALF_PI theta_ribbon_1 = (TWICE_PI * x / T) + phase_angle_ribbon_1 #Initialize ribbon1_point and ribbon2_point ribbon1_point = pointOnAxis + \ amplitudeVector * sin(theta_ribbon_1) + \ depthVector * cos(theta_ribbon_1) ribbon1_direction = +1 drawDnaSingleRibbon(glpane, endCenter1, endCenter2, basesPerTurn, duplexRise, # maybe: don't pass these three args, get from glpane # instead? [bruce 080422 comment] glpaneScale, lineOfSightVector, displayStyle, ribbon1_start_point = ribbon1_point, ribbon1_direction = ribbon1_direction, peakDeviationFromCenter = peakDeviationFromCenter, ribbonThickness = ribbonThickness, ribbon1Color = ribbon1Color, stepColor = stepColor) if ribbon2_start_point is not None: ribbon2_point = ribbon2_start_point else: if ribbon1_start_point is not None: ribbon2_point = _get_ribbon_point_on_other_ribbon( ribbon1_start_point, ribbon1_direction, endCenter1, unitVectorAlongLength) else: phase_angle_ribbon_2 = asin(-6.0/(amplitude)) theta_ribbon_2 = (TWICE_PI * x / T) - phase_angle_ribbon_2 ribbon2_point = pointOnAxis - \ amplitudeVector * sin(theta_ribbon_2) + \ depthVector * cos(theta_ribbon_2) ribbon2_direction = -1 drawDnaSingleRibbon(glpane, endCenter1, endCenter2, basesPerTurn, duplexRise, # maybe: don't pass these three args, get from glpane # instead? [bruce 080422 comment] glpaneScale, lineOfSightVector, displayStyle, ribbon1_start_point = ribbon2_point, ribbon1_direction = ribbon2_direction, peakDeviationFromCenter = peakDeviationFromCenter, ribbonThickness = ribbonThickness, ribbon1Color = ribbon2Color, stepColor = stepColor) del vectorAlongLadderStep return def _get_ribbon_point_on_other_ribbon(ribbon_start_point, ribbon_direction, endCenter1, unitVectorAlongLength): """ Given a ribbon point, return the ribbon point on the other strand (ribbon). """ other_ribbon_point = V(0, 0, 0) #Theta = 133 degree is the angle between strand1atom-axis-strand2atom #It is negative if the bond direction is negative (-1) theta = 133.0*pi/180 if ribbon_direction == -1: theta = -theta quat = Q(unitVectorAlongLength, theta) other_ribbon_point = quat.rot(ribbon_start_point - endCenter1) + endCenter1 return other_ribbon_point # end
NanoCAD-master
cad/src/graphics/drawing/drawDnaRibbons.py
""" ### This is a copy of file OpenGL/GL/ARB/shader_objects.py from ### /Library/Python/2.5/site-packages/PyOpenGL-3.0.0b3-py2.5.egg . ### It replaces the broken version in PyOpenGL-3.0.0a6-py2.5.egg . ### ### The difference between the two is mainly that the wrapper function ### definitions aren't in "if" statements checking for null (undefined) wrapper ### functions. These don't work on Windows because its dll wrappers are ### different, so none of the wrappers get defined on Windows in the a6 version. ### ### The only change to the b3 version to make it work in a6 is that two calls to ### "if OpenGL.ERROR_CHECKING:" are commented out with ### below. OpenGL extension ARB.shader_objects $version: $Id$ This module customises the behaviour of the OpenGL.raw.GL.ARB.shader_objects to provide a more Python-friendly API """ from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from OpenGL.GL import glget import ctypes from OpenGL.raw.GL.ARB.shader_objects import * import OpenGL from OpenGL import converters, error GL_INFO_LOG_LENGTH_ARB = constant.Constant( 'GL_INFO_LOG_LENGTH_ARB', 0x8B84 ) glShaderSourceARB = platform.createExtensionFunction( 'glShaderSourceARB', dll=platform.GL, resultType=None, argTypes=(constants.GLhandleARB, constants.GLsizei, ctypes.POINTER(ctypes.c_char_p), arrays.GLintArray,), doc = 'glShaderSourceARB( GLhandleARB(shaderObj), str( string) ) -> None', argNames = ('shaderObj', 'count', 'string', 'length',), ) conv = converters.StringLengths( name='string' ) glShaderSourceARB = wrapper.wrapper( glShaderSourceARB ).setPyConverter( 'count' # number of strings ).setPyConverter( 'length' # lengths of strings ).setPyConverter( 'string', conv.stringArray ).setCResolver( 'string', conv.stringArrayForC, ).setCConverter( 'length', conv, ).setCConverter( 'count', conv.totalCount, ) del conv for size in (1,2,3,4): for format,arrayType in ( ('f',arrays.GLfloatArray), ('i',arrays.GLintArray), ): name = 'glUniform%(size)s%(format)svARB'%globals() globals()[name] = arrays.setInputArraySizeType( globals()[name], size, arrayType, 'value', ) del format, arrayType del size base_glGetObjectParameterivARB = glGetObjectParameterivARB def glGetObjectParameterivARB( shader, pname ): """ Retrieve the integer parameter for the given shader """ status = arrays.GLintArray.zeros( (1,)) status[0] = 1 base_glGetObjectParameterivARB( shader, pname, status ) return status[0] glGetObjectParameterivARB.wrappedOperation = base_glGetObjectParameterivARB base_glGetObjectParameterfvARB = glGetObjectParameterfvARB def glGetObjectParameterfvARB( shader, pname ): """ Retrieve the float parameter for the given shader """ status = arrays.GLfloatArray.zeros( (1,)) status[0] = 1.0 base_glGetObjectParameterfvARB( shader, pname,status ) return status[0] glGetObjectParameterfvARB.wrappedOperation = base_glGetObjectParameterfvARB def _afterCheck( key ): """ Generate an error-checking function for compilation operations """ def GLSLCheckError( result, baseOperation=None, cArguments=None, *args ): result = error.glCheckError( result, baseOperation, cArguments, *args ) status = glGetObjectParameterivARB( cArguments[0], key ) if not status: raise error.GLError( result = result, baseOperation = baseOperation, cArguments = cArguments, description= glGetInfoLogARB( cArguments[0] ) ) return result return GLSLCheckError ###if OpenGL.ERROR_CHECKING: glCompileShaderARB.errcheck = _afterCheck( GL_OBJECT_COMPILE_STATUS_ARB ) ###if OpenGL.ERROR_CHECKING: glLinkProgramARB.errcheck = _afterCheck( GL_OBJECT_LINK_STATUS_ARB ) ## Not sure why, but these give invalid operation :( ##if glValidateProgramARB and OpenGL.ERROR_CHECKING: ## glValidateProgramARB.errcheck = _afterCheck( GL_OBJECT_VALIDATE_STATUS_ARB ) base_glGetInfoLogARB = glGetInfoLogARB def glGetInfoLogARB( obj ): """ Retrieve the program/shader's error messages as a Python string returns string which is '' if no message """ length = int(glGetObjectParameterivARB(obj, GL_INFO_LOG_LENGTH_ARB)) if length > 0: log = ctypes.create_string_buffer(length) base_glGetInfoLogARB(obj, length, None, log) return log.value.strip('\000') # null-termination return '' glGetInfoLogARB.wrappedOperation = base_glGetInfoLogARB base_glGetAttachedObjectsARB = glGetAttachedObjectsARB def glGetAttachedObjectsARB( obj ): """ Retrieve the attached objects as an array of GLhandleARB instances """ length= glGetObjectParameterivARB( obj, GL_OBJECT_ATTACHED_OBJECTS_ARB ) if length > 0: storage = arrays.GLuintArray.zeros( (length,)) base_glGetAttachedObjectsARB( obj, length, None, storage ) return storage return arrays.GLuintArray.zeros( (0,)) glGetAttachedObjectsARB.wrappedOperation = base_glGetAttachedObjectsARB base_glGetShaderSourceARB = glGetShaderSourceARB def glGetShaderSourceARB( obj ): """ Retrieve the program/shader's source code as a Python string returns string which is '' if no source code """ length = int(glGetObjectParameterivARB(obj, GL_OBJECT_SHADER_SOURCE_LENGTH_ARB)) if length > 0: source = ctypes.create_string_buffer(length) base_glGetShaderSourceARB(obj, length, None, source) return source.value.strip('\000') # null-termination return '' glGetShaderSourceARB.wrappedOperation = base_glGetShaderSourceARB base_glGetActiveUniformARB = glGetActiveUniformARB def glGetActiveUniformARB(program, index): """ Retrieve the name, size and type of the uniform of the index in the program """ max_index = int(glGetObjectParameterivARB( program, GL_OBJECT_ACTIVE_UNIFORMS_ARB )) length = int(glGetObjectParameterivARB( program, GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB)) if index < max_index and index >= 0 and length > 0: name = ctypes.create_string_buffer(length) size = arrays.GLintArray.zeros( (1,)) gl_type = arrays.GLuintArray.zeros( (1,)) base_glGetActiveUniformARB(program, index, length, None, size, gl_type, name) return name.value, size[0], gl_type[0] raise IndexError, 'Index %s out of range 0 to %i' % (index, max_index - 1, ) glGetActiveUniformARB.wrappedOperation = base_glGetActiveUniformARB
NanoCAD-master
cad/src/graphics/drawing/shader_objects_patch.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ patterned_drawing.py - special effects for highlighted/selected drawing styles @author: Russ @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: Russ 080523 wrote this [in chunk.py?] Russ 080530 refactored to move the patterned drawing style setup here [in gl_lighting.py?] from chunk.py, and generalized the prefs decoding to handle selection as well as hover highlighting. Bruce 090304 moved it into its own file to avoid a likely future import cycle (when it's supported in shaders), and since it doesn't belong in gl_lighting.py. """ from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_LINE from OpenGL.GL import glLineWidth from OpenGL.GL import GL_FILL from OpenGL.GL import GL_FRONT from OpenGL.GL import GL_BACK from OpenGL.GL import glPolygonMode from OpenGL.GL import glPolygonOffset from OpenGL.GL import GL_POLYGON_OFFSET_LINE from OpenGL.GL import GL_POLYGON_STIPPLE from OpenGL.GL import glPolygonStipple import numpy import foundation.env as env from utilities.prefs_constants import hoverHighlightingColorStyle_prefs_key from utilities.prefs_constants import HHS_SOLID, HHS_SCREENDOOR1 from utilities.prefs_constants import HHS_CROSSHATCH1, HHS_BW_PATTERN from utilities.prefs_constants import HHS_POLYGON_EDGES, HHS_HALO from utilities.prefs_constants import selectionColorStyle_prefs_key from utilities.prefs_constants import SS_SOLID, SS_SCREENDOOR1, SS_CROSSHATCH1 from utilities.prefs_constants import SS_BW_PATTERN, SS_POLYGON_EDGES, SS_HALO from utilities.prefs_constants import haloWidth_prefs_key # == # 32x32 stipple bitmask patterns, in C arrays. # To avoid "seams", repeated subpattern sizes must be a power of 2. # _ScreenDoor - 2x2 repeat, 1/4 density (one corner turned on.) _ScreenDoor = numpy.array(16*(4*[0xaa] + 4*[0x00]), dtype = numpy.uint8) # _CrossHatch - 4x4 repeat, 7/16 density (two edges of a square turned on.) _CrossHatch = numpy.array(8*(4*[0xff] + 12*[0x11]), dtype = numpy.uint8) # == def _decodePatternPrefs(highlight = False, select = False): """ Internal common code for startPatternedDrawing and endPatternedDrawing. Returns a tuple of prefs data. """ key = (highlight and hoverHighlightingColorStyle_prefs_key or select and selectionColorStyle_prefs_key) # False or string. style = bool(key) and env.prefs[key] # False or enum string. solid = style == False or (highlight and style == HHS_SOLID or select and style == SS_SOLID) # bool. pattern = None # None or a bitarray pointer. edges = halos = False # bool. # Nothing to do for solid colors. if not solid: # Check for stipple-patterned drawing styles. if (highlight and style == HHS_SCREENDOOR1 or select and style == SS_SCREENDOOR1): pattern = _ScreenDoor pass elif (highlight and style == HHS_CROSSHATCH1 or select and style == SS_CROSSHATCH1): pattern = _CrossHatch pass # Check for polygon-edge drawing styles. if pattern is None: edges = (highlight and style == HHS_POLYGON_EDGES or select and style == SS_POLYGON_EDGES) halos = (highlight and style == HHS_HALO or select and style == SS_HALO) pass pass return (key, style, solid, pattern, edges, halos) def isPatternedDrawing(highlight = False, select = False): """ Return True if either highlight or select is passed as True, and the corresponding preference is set to select a patterned (non-solid) drawing style. """ (key, style, solid, pattern, edges, halos) = \ _decodePatternPrefs(highlight, select) return not solid def startPatternedDrawing(highlight = False, select = False): """ Start drawing with a patterned style, if either highlight or select is passed as True, and the corresponding preference is set to select a patterned drawing style. This is common code for two different prefs keys, each of which has its own set of settings constants... Return value is True if one of the patterned styles is selected. """ (key, style, solid, pattern, edges, halos) = \ _decodePatternPrefs(highlight, select) if solid: # Nothing to do here for solid colors. return False # Set up stipple-patterned drawing styles. if pattern is not None: glEnable(GL_POLYGON_STIPPLE) glPolygonStipple(pattern) return True # Both polygon edges and halos are drawn in line-mode. if edges or halos: glPolygonMode(GL_FRONT, GL_LINE) glPolygonMode(GL_BACK, GL_LINE) if halos: # Draw wide, unshaded lines, offset a little bit away from the # viewer so that only the silhouette edges are visible. glDisable(GL_LIGHTING) glLineWidth(env.prefs[haloWidth_prefs_key]) glEnable(GL_POLYGON_OFFSET_LINE) glPolygonOffset(0.0, 5.e4) # Constant offset. pass pass return True def endPatternedDrawing(highlight = False, select = False): """ End drawing with a patterned style, if either highlight or select is passed as True, and the corresponding preference is set to select a patterned drawing style. This is common code for two different prefs keys, each of which has its own set of settings constants... Return value is True if one of the patterned styles is selected. """ (key, style, solid, pattern, edges, halos) = \ _decodePatternPrefs(highlight, select) if solid: # Nothing to do here for solid colors. return False # End stipple-patterned drawing styles. if pattern is not None: glDisable(GL_POLYGON_STIPPLE) return True # End line-mode for polygon-edges or halos styles. if edges or halos: glPolygonMode(GL_FRONT, GL_FILL) glPolygonMode(GL_BACK, GL_FILL) if halos: # Back to normal lighting and treatment of lines and polygons. glEnable(GL_LIGHTING) glLineWidth(1.0) glDisable(GL_POLYGON_OFFSET_LINE) glPolygonOffset(0.0, 0.0) pass pass return True # end
NanoCAD-master
cad/src/graphics/drawing/patterned_drawing.py
""" # Patch the gle[GS]etNumSides functions to call gle[GS]etNumSlices. $Id$ # The following was extracted and modified from gle[GS]etNumSides in # /Library/Python/2.5/site-packages/PyOpenGL-3.0.0a6-py2.5.egg/ # OpenGL/raw/GLE/__init__.py """ # Patch the gle[GS]etNumSides functions to call gle[GS]etNumSlices. # # This can be loaded only if needed, for example: # try: # from OpenGL.GLE import gleGetNumSides, gleSetNumSides # except: # print "GLE module can't be imported. Now trying _GLE" # from OpenGL._GLE import gleGetNumSides, gleSetNumSides # if not bool(gleGetNumSides): # from graphics.drawing.gleNumSides_patch import gleGetNumSides # from graphics.drawing.gleNumSides_patch import gleSetNumSides # Only the interface to gle[GS]etNumSides is in PyOpenGL-3.0.0a6. # On 10.5.2 (Leoplard), only gle[GS]etNumSlices is in the shared lib file: # /System/Library/Frameworks/glut.framework/glut . # # Maybe Apple had included an earlier version of GLE in the Mac port. # GLE was not actually not an official part of OpenGL until GLUT 3.6: # http://www.opengl.org/resources/libraries/glut/glut_downloads.php#3.6 # # Linas Vesptas's GLE Tubing and Extrusion library # <http://linas.org/gle/index.html> with documentation and example # programs is now a part of GLUT. # The following was extracted and modified from gle[GS]etNumSides in # /Library/Python/2.5/site-packages/PyOpenGL-3.0.0a6-py2.5.egg/ # OpenGL/raw/GLE/__init__.py from ctypes import c_int from OpenGL import platform, arrays from OpenGL.constant import Constant # not used -- what is it? from OpenGL import constants as GLconstants # /usr/include/GL/gle.h 114 gleGetNumSides = platform.createBaseFunction( 'gleGetNumSlices', dll=platform.GLE, resultType=c_int, argTypes=[], doc='gleGetNumSlices( ) -> c_int', argNames=(), ) # /usr/include/GL/gle.h 115 gleSetNumSides = platform.createBaseFunction( 'gleSetNumSlices', dll=platform.GLE, resultType=None, argTypes=[c_int], doc='gleSetNumSlices( c_int(slices) ) -> None', argNames=('slices',), )
NanoCAD-master
cad/src/graphics/drawing/gleNumSides_patch.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ dimensions.py - code to help draw dimensions $Id$ History: wware 060324 - created this file bruce 071030 - split Font3D out of dimensions module (since used in drawer.py) """ __author__ = "Will" import math import Numeric from Numeric import dot from utilities import debug_flags from geometry.VQT import cross from geometry.VQT import vlen from geometry.VQT import norm from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.Font3D import Font3D, WIDTH, HEIGHT # TODO: WIDTH, HEIGHT should be Font3D attributes [bruce 071030 comment] class ZeroLengthCylinder(Exception): pass class CylindricalCoordinates: def __init__(self, point0, z, uhint, uhint2): # u and v and zn are unit vectors # z is NOT a unit vector self.p0 = point0 self.p1 = point1 = point0 + z self.z = z zlen = vlen(z) if zlen < 1.0e-6: raise ZeroLengthCylinder() self.zinv = 1.0 / zlen self.zn = zn = norm(z) u = norm(uhint - (dot(uhint, z) / zlen**2) * z) if vlen(u) < 1.0e-4: u = norm(uhint2 - (dot(uhint2, z) / zlen**2) * z) v = cross(zn, u) self.u = u self.v = v def __repr__(self): def vecrepr(v): return "[%g %g %g]" % tuple(v) return ("<CylindricalCoordinates p0=%s p1=%s\n z=%s u=%s v=%s>" % (vecrepr(self.p0), vecrepr(self.p1), vecrepr(self.z), vecrepr(self.u), vecrepr(self.v))) def rtz(self, pt): d = pt - self.p0 z = dot(d, self.zn) d = d - z * self.zn r = vlen(d) theta = Numeric.arctan2(dot(d, self.v), dot(d, self.u)) return Numeric.array((r, theta, z), 'd') def xyz(self, rtz): r, t, z = rtz du = (r * math.cos(t)) * self.u dv = (r * math.sin(t)) * self.v dz = z * self.z return self.p0 + du + dv + dz def drawLine(self, color, rtz1, rtz2, width=1): drawline(color, self.xyz(rtz1), self.xyz(rtz2), width=width) def drawArc(self, color, r, theta1, theta2, z, width=1, angleIncrement = math.pi / 50): n = int(math.fabs(theta2 - theta1) / angleIncrement + 1) step = (1.0 * theta2 - theta1) / n for i in range(n): t = theta1 + step self.drawLine(color, (r, theta1, z), (r, t, z), width=width) theta1 = t THICKLINEWIDTH = 20 def drawLinearDimension(color, # what color are we drawing this in right, up, # screen directions mapped to xyz coords bpos, # position of the handle for moving the text p0, p1, # positions of the ends of the dimension text, highlighted=False): outOfScreen = cross(right, up) bdiff = bpos - 0.5 * (p0 + p1) csys = CylindricalCoordinates(p0, p1 - p0, bdiff, right) # This works OK until we want to keep the text right side up, then the # criterion for right-side-up-ness changes because we've changed 'up'. br, bt, bz = csys.rtz(bpos) e0 = csys.xyz((br + 0.5, 0, 0)) e1 = csys.xyz((br + 0.5, 0, 1)) drawline(color, p0, e0) drawline(color, p1, e1) v0 = csys.xyz((br, 0, 0)) v1 = csys.xyz((br, 0, 1)) if highlighted: drawline(color, v0, v1, width=THICKLINEWIDTH) else: drawline(color, v0, v1) # draw arrowheads at the ends a1, a2 = 0.25, 1.0 * csys.zinv arrow00 = csys.xyz((br + a1, 0, a2)) arrow01 = csys.xyz((br - a1, 0, a2)) drawline(color, v0, arrow00) drawline(color, v0, arrow01) arrow10 = csys.xyz((br + a1, 0, 1-a2)) arrow11 = csys.xyz((br - a1, 0, 1-a2)) drawline(color, v1, arrow10) drawline(color, v1, arrow11) # draw the text for the numerical measurement, make # sure it goes from left to right xflip = dot(csys.z, right) < 0 # then make sure it's right side up theoreticalRight = (xflip and -csys.z) or csys.z theoreticalOutOfScreen = cross(theoreticalRight, bdiff) yflip = dot(theoreticalOutOfScreen, outOfScreen) < 0 if debug_flags.atom_debug: print "DEBUG INFO FROM drawLinearDimension" print csys print theoreticalRight, theoreticalOutOfScreen print xflip, yflip if yflip: def fx(y): return br + 1.5 - y / (1. * HEIGHT) else: def fx(y): return br + 0.5 + y / (1. * HEIGHT) if xflip: def fz(x): return 0.9 - csys.zinv * x / (1. * WIDTH) else: def fz(x): return 0.1 + csys.zinv * x / (1. * WIDTH) def tfm(x, y, fx=fx, fz=fz): return csys.xyz((fx(y), 0, fz(x))) f3d = Font3D() f3d.drawString(text, tfm=tfm, color=color) def drawAngleDimension(color, right, up, bpos, p0, p1, p2, text, minR1=0.0, minR2=0.0, highlighted=False): z = cross(p0 - p1, p2 - p1) try: csys = CylindricalCoordinates(p1, z, up, right) except ZeroLengthCylinder: len0 = vlen(p1 - p0) len2 = vlen(p1 - p2) # make sure it's really a zero-degree angle assert len0 > 1.0e-6 assert len2 > 1.0e-6 assert vlen(cross(p1 - p2, p1 - p0)) < 1.0e-6 # For an angle of zero degrees, there is no correct way to # orient the text, so just draw a line segment if len0 > len2: L = len0 end = p0 else: L = len2 end = p2 Lb = vlen(bpos - p1) if Lb > L: L = Lb end = p1 + (Lb / L) * (end - p1) drawline(color, p1, end) return br, bt, bz = csys.rtz(bpos) theta1 = csys.rtz(p0)[1] theta2 = csys.rtz(p2)[1] if theta2 < theta1 - math.pi: theta2 += 2 * math.pi elif theta2 > theta1 + math.pi: theta2 -= 2 * math.pi if theta2 < theta1: theta1, theta2 = theta2, theta1 e0 = csys.xyz((max(vlen(p0 - p1), br, minR1) + 0.5, theta1, 0)) e1 = csys.xyz((max(vlen(p2 - p1), br, minR2) + 0.5, theta2, 0)) drawline(color, p1, e0) drawline(color, p1, e1) if highlighted: csys.drawArc(color, br, theta1, theta2, 0, width=THICKLINEWIDTH) else: csys.drawArc(color, br, theta1, theta2, 0) # draw some arrowheads e00 = csys.xyz((br, theta1, 0)) e10 = csys.xyz((br, theta2, 0)) dr = 0.25 dtheta = 1 / br e0a = csys.xyz((br + dr, theta1 + dtheta, 0)) e0b = csys.xyz((br - dr, theta1 + dtheta, 0)) e1a = csys.xyz((br + dr, theta2 - dtheta, 0)) e1b = csys.xyz((br - dr, theta2 - dtheta, 0)) drawline(color, e00, e0a) drawline(color, e00, e0b) drawline(color, e10, e1a) drawline(color, e10, e1b) midangle = (theta1 + theta2) / 2 tmidpoint = csys.xyz((br + 0.5, midangle, 0)) h = 1.0e-3 textx = norm(csys.xyz((br + 0.5, midangle + h, 0)) - tmidpoint) texty = norm(csys.xyz((br + 0.5 + h, midangle, 0)) - tmidpoint) # make sure the text runs from left to right if dot(textx, right) < 0: textx = -textx # make sure the text isn't upside-down outOfScreen = cross(right, up) textForward = cross(textx, texty) if dot(outOfScreen, textForward) < 0: tmidpoint = csys.xyz((br + 1.5, midangle, 0)) texty = -texty textxyz = tmidpoint - (0.5 * len(text)) * textx def tfm(x, y): x = (x / (1. * WIDTH)) * textx y = (y / (1. * HEIGHT)) * texty return textxyz + x + y f3d = Font3D() f3d.drawString(text, tfm=tfm, color=color) def drawDihedralDimension(color, right, up, bpos, p0, p1, p2, p3, text, highlighted=False): # Draw a frame of lines that shows how the four atoms are connected # to the dihedral angle csys = CylindricalCoordinates(p1, p2 - p1, up, right) r1, theta1, z1 = csys.rtz(p0) r2, theta2, z2 = csys.rtz(p3) e0a = csys.xyz((r1, theta1, 0.5)) e1a = csys.xyz((r2, theta2, 0.5)) drawline(color, p1, p0) drawline(color, p0, e0a) drawline(color, p3, e1a) drawline(color, p2, p3) drawline(color, p1, p2) # Use the existing angle drawing routine to finish up drawAngleDimension(color, right, up, bpos, e0a, (p1 + p2) / 2, e1a, text, minR1=r1, minR2=r2, highlighted=highlighted) # end
NanoCAD-master
cad/src/graphics/drawing/dimensions.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ Draws the DNA in a ladder display where each strand is represented as a ladder beam and each step represents duplex rise. @author: Ninad @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ @license: GPL """ import foundation.env as env from Numeric import pi ONE_RADIAN = 180.0 / pi HALF_PI = pi/2.0 TWICE_PI = 2*pi from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushMatrix from OpenGL.GL import glTranslatef from graphics.drawing.drawers import drawArrowHead from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.drawers import drawPoint from geometry.VQT import norm, vlen, V, cross from utilities.prefs_constants import DarkBackgroundContrastColor_prefs_key def drawDnaLadder(endCenter1, endCenter2, duplexRise, glpaneScale, lineOfSightVector, ladderWidth = 17.0, beamThickness = 2.0, beam1Color = None, beam2Color = None, stepColor = None ): """ Draws the DNA in a ladder display where each strand is represented as a ladder beam and each step represents duplex rise. @param endCenter1: Ladder center at end 1 @type endCenter1: B{V} @param endCenter2: Ladder center at end 2 @type endCenter2: B{V} @param duplexRise: Center to center distance between consecutive steps @type duplexRise: float @param glpaneScale: GLPane scale used in scaling arrow head drawing @type glpaneScale: float @param lineOfSightVector: Glpane lineOfSight vector, used to compute the the vector along the ladder step. @type: B{V} @param ladderWidth: width of the ladder @type ladderWidth: float @param beamThickness: Thickness of the two ladder beams @type beamThickness: float @param beam1Color: Color of beam1 @param beam2Color: Color of beam2 @see: B{DnaLineMode.Draw } (where it is used) for comments on color convention """ ladderLength = vlen(endCenter1 - endCenter2) #Don't draw the vertical line (step) passing through the startpoint unless #the ladderLength is atleast equal to the duplexRise. # i.e. do the drawing only when there are atleast two ladder steps. # This prevents a 'revolving line' effect due to the single ladder step at # the first endpoint if ladderLength < duplexRise: return if beam1Color is None: beam1Color = env.prefs[DarkBackgroundContrastColor_prefs_key] if beam2Color is None: beam2Color = env.prefs[DarkBackgroundContrastColor_prefs_key] if stepColor is None: stepColor = env.prefs[DarkBackgroundContrastColor_prefs_key] unitVector = norm(endCenter2 - endCenter1) glDisable(GL_LIGHTING) glPushMatrix() glTranslatef(endCenter1[0], endCenter1[1], endCenter1[2]) pointOnAxis = V(0, 0, 0) vectorAlongLadderStep = cross(-lineOfSightVector, unitVector) unitVectorAlongLadderStep = norm(vectorAlongLadderStep) ladderBeam1Point = pointOnAxis + unitVectorAlongLadderStep*0.5*ladderWidth ladderBeam2Point = pointOnAxis - unitVectorAlongLadderStep*0.5*ladderWidth #Following limits the arrowHead Size to the given value. When you zoom out, #the rest of ladder drawing becomes smaller (expected) and the following #check ensures that the arrowheads are drawn proportinately. # (Not using a 'constant' to do this as using glpaneScale gives better #results) if glpaneScale > 40: arrowDrawingScale = 40 else: arrowDrawingScale = glpaneScale #Draw the arrow head on beam1 drawArrowHead(beam2Color, ladderBeam2Point, arrowDrawingScale, -unitVectorAlongLadderStep, - unitVector) x = 0.0 while x < ladderLength: drawPoint(stepColor, pointOnAxis) previousPoint = pointOnAxis previousLadderBeam1Point = ladderBeam1Point previousLadderBeam2Point = ladderBeam2Point pointOnAxis = pointOnAxis + unitVector*duplexRise x += duplexRise ladderBeam1Point = previousPoint + \ unitVectorAlongLadderStep*0.5*ladderWidth ladderBeam2Point = previousPoint - \ unitVectorAlongLadderStep*0.5*ladderWidth if previousLadderBeam1Point: drawline(beam1Color, previousLadderBeam1Point, ladderBeam1Point, width = beamThickness, isSmooth = True ) drawline(beam2Color, previousLadderBeam2Point, ladderBeam2Point, width = beamThickness, isSmooth = True ) drawline(stepColor, ladderBeam1Point, ladderBeam2Point) drawArrowHead(beam1Color, ladderBeam1Point, arrowDrawingScale, unitVectorAlongLadderStep, unitVector) glPopMatrix() glEnable(GL_LIGHTING)
NanoCAD-master
cad/src/graphics/drawing/drawDnaLadder.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ gl_lighting.py - Lights, materials, and special effects (fog). @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originated by Josh in drawer.py . Various developers extended it since then. Brad G. added ColorSorter features and probably apply_material. 080519 russ: pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py """ from OpenGL.GL import GL_AMBIENT from OpenGL.GL import GL_AMBIENT_AND_DIFFUSE from OpenGL.GL import glColor4fv from OpenGL.GL import GL_CONSTANT_ATTENUATION from OpenGL.GL import GL_DIFFUSE from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_FOG from OpenGL.GL import GL_FOG_COLOR from OpenGL.GL import GL_FOG_END from OpenGL.GL import GL_FOG_MODE from OpenGL.GL import GL_FOG_START from OpenGL.GL import GL_FRONT_AND_BACK from OpenGL.GL import GL_LIGHT0 from OpenGL.GL import GL_LIGHT1 from OpenGL.GL import GL_LIGHT2 from OpenGL.GL import glLightf from OpenGL.GL import glLightfv from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_LINEAR from OpenGL.GL import glLoadIdentity from OpenGL.GL import glMaterialf from OpenGL.GL import glMaterialfv from OpenGL.GL import glMatrixMode from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_POSITION from OpenGL.GL import GL_SHININESS from OpenGL.GL import GL_SPECULAR try: from OpenGL.GL import glFog from OpenGL.GL import glFogv # piotr 080515 except: # The installed version of OpenGL requires argument-typed glFog calls. from OpenGL.GL import glFogf as glFog from OpenGL.GL import glFogfv as glFogv pass from utilities.constants import white from utilities.debug import print_compact_traceback import graphics.drawing.drawing_globals as drawing_globals # only for glprefs in apply_material # == # Helper functions for use by GL widgets wanting to set up lighting. #bruce 051212 made these from the code in GLPane which now calls them, so they #can also be used in ThumbView # Default lights tuples (format is as used by setup_standard_lights; perhaps # also assumed by other code). #grantham 20051121 comment - Light should probably be a class. Right now, # changing the behavior of lights requires changing a bunch of # ambiguous tuples and tuple packing/unpacking. #bruce 051212 moved this here from GLPane; maybe it belongs in prefs_constants # instead? # Note: I'm not sure whether this is the only place where this data is coded. _default_lights = ((white, 0.1, 0.5, 0.5, -50, 70, 30, True), (white, 0.1, 0.5, 0.5, -20, 20, 20, True), (white, 0.1, 0.1, 0.1, 0, 0, 100, False)) # for each of 3 lights, this stores ((r,g,b),a,d,s,x,y,z,e) # revised format to include s,x,y,z. Mark 051202. # revised format to include c (r,g,b). Mark 051204. # Be sure to keep the lightColor prefs keys and _lights colors # synchronized. # Mark 051204. [a comment from when this was located in GLPane] def glprefs_data_used_by_setup_standard_lights( glprefs): #bruce 051212 """ Return a summary of the glprefs data used by setup_standard_lights (when that was passed the same glprefs argument). """ # This must be kept in sync with what's used by setup_standard_lights() . return (glprefs.override_light_specular,) def setup_standard_lights( lights, glprefs): """ Set up lighting in the current GL context using the supplied "lights" tuple (in the format used by GLPane's prefs) and the required glprefs object (of class GLPrefs). @note: the glprefs data used can be summarized by the related function glprefs_data_used_by_setup_standard_lights (which see). @warning: has side effects on GL_MODELVIEW matrix. @note: If GL_NORMALIZE needs to be enabled, callers should do that themselves, since this depends on what they will draw and might slow down drawing. """ assert glprefs is not None # note: whatever glprefs data is used below must also be present # in the return value of glprefs_data_used_by_setup_standard_lights(). # [bruce 051212] #e not sure whether projection matrix also needs to be reset here # [bruce 051212] glMatrixMode(GL_MODELVIEW) glLoadIdentity() try: # new code (((r0,g0,b0),a0,d0,s0,x0,y0,z0,e0), \ ( (r1,g1,b1),a1,d1,s1,x1,y1,z1,e1), \ ( (r2,g2,b2),a2,d2,s2,x2,y2,z2,e2)) = lights # Great place for a print statement for debugging lights. Keep this. # Mark 051204. [revised by bruce 051212] #print "-------------------------------------------------------------" #print "setup_standard_lights: lights[0]=", lights[0] #print "setup_standard_lights: lights[1]=", lights[1] #print "setup_standard_lights: lights[2]=", lights[2] glLightfv(GL_LIGHT0, GL_POSITION, (x0, y0, z0, 0)) glLightfv(GL_LIGHT0, GL_AMBIENT, (r0*a0, g0*a0, b0*a0, 1.0)) glLightfv(GL_LIGHT0, GL_DIFFUSE, (r0*d0, g0*d0, b0*d0, 1.0)) if glprefs.override_light_specular is not None: glLightfv(GL_LIGHT0, GL_SPECULAR, glprefs.override_light_specular) else: # grantham 20051121 - this should be a component on its own # not replicating the diffuse color. # Added specular (s0) as its own component. mark 051202. glLightfv(GL_LIGHT0, GL_SPECULAR, (r0*s0, g0*s0, b0*s0, 1.0)) glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.0) glLightfv(GL_LIGHT1, GL_POSITION, (x1, y1, z1, 0)) glLightfv(GL_LIGHT1, GL_AMBIENT, (r1*a1, g1*a1, b1*a1, 1.0)) glLightfv(GL_LIGHT1, GL_DIFFUSE, (r1*d1, g1*d1, b1*d1, 1.0)) if glprefs.override_light_specular is not None: glLightfv(GL_LIGHT1, GL_SPECULAR, glprefs.override_light_specular) else: glLightfv(GL_LIGHT1, GL_SPECULAR, (r1*s1, g1*s1, b1*s1, 1.0)) glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 1.0) glLightfv(GL_LIGHT2, GL_POSITION, (x2, y2, z2, 0)) glLightfv(GL_LIGHT2, GL_AMBIENT, (r2*a2, g2*a2, b2*a2, 1.0)) glLightfv(GL_LIGHT2, GL_DIFFUSE, (r2*d2, g2*d2, b2*d2, 1.0)) if glprefs.override_light_specular is not None: glLightfv(GL_LIGHT2, GL_SPECULAR, glprefs.override_light_specular) else: glLightfv(GL_LIGHT2, GL_SPECULAR, (r2*s2, g2*s2, b2*s2, 1.0)) glLightf(GL_LIGHT2, GL_CONSTANT_ATTENUATION, 1.0) glEnable(GL_LIGHTING) if e0: glEnable(GL_LIGHT0) else: glDisable(GL_LIGHT0) if e1: glEnable(GL_LIGHT1) else: glDisable(GL_LIGHT1) if e2: glEnable(GL_LIGHT2) else: glDisable(GL_LIGHT2) except: print_compact_traceback( "bug (worked around): setup_standard_lights reverting to old code.") # old code, used only to set up some sort of workable lighting in case # of bugs (this is not necessarily using the same values as # _default_lights; doesn't matter since never used unless there are # bugs) glLightfv(GL_LIGHT0, GL_POSITION, (-50, 70, 30, 0)) glLightfv(GL_LIGHT0, GL_AMBIENT, (0.3, 0.3, 0.3, 1.0)) glLightfv(GL_LIGHT0, GL_DIFFUSE, (0.8, 0.8, 0.8, 1.0)) glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.0) glLightfv(GL_LIGHT1, GL_POSITION, (-20, 20, 20, 0)) glLightfv(GL_LIGHT1, GL_AMBIENT, (0.4, 0.4, 0.4, 1.0)) glLightfv(GL_LIGHT1, GL_DIFFUSE, (0.4, 0.4, 0.4, 1.0)) glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 1.0) glLightfv(GL_LIGHT2, GL_POSITION, (0, 0, 100, 0)) glLightfv(GL_LIGHT2, GL_AMBIENT, (1.0, 1.0, 1.0, 1.0)) glLightfv(GL_LIGHT2, GL_DIFFUSE, (1.0, 1.0, 1.0, 1.0)) glLightf(GL_LIGHT2, GL_CONSTANT_ATTENUATION, 1.0) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_LIGHT1) glDisable(GL_LIGHT2) return # from setup_standard_lights # == def setup_fog(fog_start, fog_end, fog_color): glFog(GL_FOG_MODE, GL_LINEAR) glFog(GL_FOG_START, fog_start) glFog(GL_FOG_END, fog_end) if len(fog_color) == 3: fog_color = (fog_color[0], fog_color[1], fog_color[2], 1.0) glFogv(GL_FOG_COLOR, fog_color) # piotr 080515 def enable_fog(): glEnable(GL_FOG) def disable_fog(): glDisable(GL_FOG) # == # grantham 20051121, renamed 20051201; revised by bruce 051126, 051203 (added # specular_brightness), 051215, 090304 (added optional glprefs arg) ### REVIEW: should apply_material be a method of GLPrefs and perhaps GLPane? # Or at least, should its glprefs arg be required (removing the last use of # drawing_globals in this module)? [And in the meantime, moved to that module?] # # Probably yes, but making all uses know glprefs requires passing glpane or glprefs # args or attrs into quite a few functions or methods or instances that don't # have them yet, including at least CSDL, which ought to have a glprefs or glpane # attr for use in .draw (as well as a GL resource context attr for other reasons), # and the bond drawing code. So I don't quite have time to do it now. But it would # be a good refactoring to do, for itself and to help refactor other things, and # not too hard to do when someone has time. [bruce 090304 comment] def apply_material(color, glprefs = None): # todo: move into glprefs.py (see comment above for why) """ In the current GL context, set material parameters based on the given color (length 3 or 4) and the material-related prefs values in glprefs (which defaults to drawing_globals.glprefs). """ if glprefs is None: glprefs = drawing_globals.glprefs pass #bruce 051215: make sure color is a tuple, and has length exactly 4, for all # uses inside this function, assuming callers pass sequences of length 3 or # 4. Needed because glMaterial requires four-component vector and PyOpenGL # doesn't check. [If this is useful elsewhere, we can split it into a # separate function.] color = tuple(color) if len(color) == 3: color = color + (1.0,) # usual case elif len(color) != 4: # should never happen; if it does, this assert will always fail assert len(color) in [3,4], \ "color tuples must have length 3 or 4, unlike %r" % (color,) glColor4fv(color) # For drawing lines with lighting disabled. if not glprefs.enable_specular_highlights: glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) # glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, (0,0,0,1)) return glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) whiteness = glprefs.specular_whiteness brightness = glprefs.specular_brightness if whiteness == 1.0: specular = (1.0, 1.0, 1.0, 1.0) # optimization else: if whiteness == 0.0: specular = color # optimization else: # assume color[3] (alpha) is not passed or is always 1.0 c1 = 1.0 - whiteness specular = ( c1 * color[0] + whiteness, c1 * color[1] + whiteness, c1 * color[2] + whiteness, 1.0 ) if brightness != 1.0: specular = ( specular[0] * brightness, specular[1] * brightness, specular[2] * brightness, 1.0 ) #e Could optimize by merging this with above 3 cases (or, of course, # by doing it in C, which we'll do eventually.) glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular) glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, glprefs.specular_shininess) return # end
NanoCAD-master
cad/src/graphics/drawing/gl_lighting.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ CS_draw_primitives.py - Public entry points for ColorSorter drawing primitives. These functions all call ColorSorter.schedule_* methods, which record object data for sorting, including the object color and an eventual call on the appropriate drawing worker function. @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originated by Josh in drawer.py . Various developers extended it since then, including Brad G (ColorSorter). 080311 piotr Added a "drawpolycone_multicolor" function for drawing polycone tubes with per-vertex colors (necessary for DNA display style) 080420 piotr Solved highlighting and selection problems for multi-colored objects (e.g. rainbow colored DNA structures). 080519 russ pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py """ from OpenGL.GL import GL_BACK from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_FILL from OpenGL.GL import GL_FRONT from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_LINE from OpenGL.GL import glPolygonMode from geometry.VQT import norm, vlen import utilities.debug as debug # for debug.print_compact_traceback from graphics.drawing.ColorSorter import ColorSorter from graphics.drawing.drawers import drawPoint from graphics.drawing.gl_GLE import gleSetNumSides def drawsphere(color, pos, radius, detailLevel, opacity = 1.0, testloop = 0 ): """ Schedule a sphere for rendering whenever ColorSorter thinks is appropriate. @param detailLevel: 0 (icosahedron), or 1 (4x as many triangles), or 2 (16x as many triangles) @type detailLevel: int (0, 1, or 2) """ ColorSorter.schedule_sphere( color, pos, radius, detailLevel, # see: _NUM_SPHERE_SIZES, len(drawing_globals.sphereList) opacity = opacity, testloop = testloop ) def drawwiresphere(color, pos, radius, detailLevel = 1): """ Schedule a wireframe sphere for rendering whenever ColorSorter thinks is appropriate. """ ColorSorter.schedule_wiresphere(color, pos, radius, detailLevel = detailLevel) def drawcylinder(color, pos1, pos2, radius, capped = 0, opacity = 1.0): """ Schedule a cylinder for rendering whenever ColorSorter thinks is appropriate. """ if 1: #bruce 060304 optimization: don't draw zero-length or almost-zero-length # cylinders. (This happens a lot, apparently for both long-bond # indicators and for open bonds. The callers hitting this should be # fixed directly! That might provide a further optim by making a lot # more single bonds draw as single cylinders.) The reason the # threshhold depends on capped is in case someone draws a very thin # cylinder as a way of drawing a disk. But they have to use some # positive length (or the direction would be undefined), so we still # won't permit zero-length then. cyllen = vlen(pos1 - pos2) if cyllen < (capped and 0.000000000001 or 0.0001): # Uncomment this to find the callers that ought to be optimized. #e optim or remove this test; until then it's commented out. ## if env.debug(): ## print ("skipping drawcylinder since length is only %5g" % ## (cyllen,)), \ ## (" (color is (%0.2f, %0.2f, %0.2f))" % ## (color[0], color[1], color[2])) return pass ColorSorter.schedule_cylinder(color, pos1, pos2, radius, capped = capped, opacity = opacity) def drawcylinder_wireframe(color, end1, end2, radius): #bruce 060608 """ Draw a wireframe cylinder (not too pretty, definitely could look nicer, but it works.) """ # display polys as their edges (see drawer.py's drawwirecube or Jig.draw for # related code) (probably we should instead create a suitable lines display # list, or even use a wire-frame-like texture so various lengths work well) glPolygonMode(GL_FRONT, GL_LINE) glPolygonMode(GL_BACK, GL_LINE) glDisable(GL_LIGHTING) # This makes motors look too busy, but without it, they look too weird # (which seems worse.) glDisable(GL_CULL_FACE) try: ##k Not sure if this color will end up controlling the edge color; we ## hope it will. drawcylinder(color, end1, end2, radius) except: debug.print_compact_traceback("bug, ignored: ") # The following assumes that we are never called as part of a jig's drawing # method, or it will mess up drawing of the rest of the jig if it's # disabled. glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glPolygonMode(GL_FRONT, GL_FILL) glPolygonMode(GL_BACK, GL_FILL) # could probably use GL_FRONT_AND_BACK return def drawDirectionArrow(color, tailPoint, arrowBasePoint, tailRadius, scale, tailRadiusLimits = (), flipDirection = False, opacity = 1.0, numberOfSides = 20, glpane = None, scale_to_glpane = False ): """ Draw a directional arrow staring at <tailPoint> with an endpoint decided by the vector between <arrowBasePoint> and <tailPoint> and the glpane scale <scale> @param color : The arrow color @type color: Array @param tailPoint: The point on the arrow tail where the arrow begins. @type tailPoint: V @param arrowBasePoint: A point on the arrow where the arrow head begins(?? @type arrowBasePoint: V @param tailRadius: The radius of the arrow tail (cylinder radius representing the arrow tail) @type tailRaius: float @param opacity: The opacity decides the opacity (or transparent display) of the rendered arrow. By default it is rendered as a solid arrow. It varies between 0.0 to 1.0 ... 1.0 represents the solid arrow renderring style @type opacity: float @param numberOfSides: The total number of sides for the arrow head (a glePolycone) The default value if 20 (20 sided polycone) @type numberOfSides: int @param scale_to_glpane: If True, the arrow size will be determined by the glpane scale. """ #@See DnaSegment_ResizeHandle to see how the tailRadiusLimits #are defined. See also exprs.Arrow. Note that we are not using #argument 'scale' for this purpose because the if scale_to_glpane and glpane is not None: scaled_tailRadius = tailRadius*0.05*glpane.scale if tailRadiusLimits: min_tailRadius = tailRadiusLimits[0] max_tailRadius = tailRadiusLimits[1] if scaled_tailRadius < min_tailRadius: pass #use the provided tailRadius elif scaled_tailRadius > max_tailRadius: tailRadius = max_tailRadius else: tailRadius = scaled_tailRadius else: tailRadius = scaled_tailRadius vec = arrowBasePoint - tailPoint vec = scale*0.07*vec arrowBase = tailRadius*3.0 arrowHeight = arrowBase*1.5 axis = norm(vec) #as of 2008-03-03 scaledBasePoint is not used so commenting out. #(will be removed after more testing) ##scaledBasePoint = tailPoint + vlen(vec)*axis drawcylinder(color, tailPoint, arrowBasePoint, tailRadius, capped = True, opacity = opacity) ##pos = scaledBasePoint pos = arrowBasePoint arrowRadius = arrowBase gleSetNumSides(numberOfSides) drawpolycone(color, # Point array (the two endpoints not drawn.) [[pos[0] - 1 * axis[0], pos[1] - 1 * axis[1], pos[2] - 1 * axis[2]], [pos[0],# - axis[0], pos[1], #- axis[1], pos[2]], #- axis[2], [pos[0] + arrowHeight * axis[0], pos[1] + arrowHeight * axis[1], pos[2] + arrowHeight * axis[2]], [pos[0] + (arrowHeight + 1) * axis[0], pos[1] + (arrowHeight + 1) * axis[1], pos[2] + (arrowHeight + 1) * axis[2]]], [arrowRadius, arrowRadius, 0, 0], # Radius array opacity = opacity ) #reset the gle number of sides to the gle default of '20' gleSetNumSides(20) def drawpolycone(color, pos_array, rad_array, opacity = 1.0): """Schedule a polycone for rendering whenever ColorSorter thinks is appropriate.""" ColorSorter.schedule_polycone(color, pos_array, rad_array, opacity = opacity) def drawpolycone_multicolor(color, pos_array, color_array, rad_array, opacity = 1.0): """Schedule a polycone for rendering whenever ColorSorter thinks is appropriate. Accepts color_array for per-vertex coloring. """ ColorSorter.schedule_polycone_multicolor(color, pos_array, color_array, rad_array, opacity = opacity) def drawsurface(color, pos, radius, tm, nm): """ Schedule a surface for rendering whenever ColorSorter thinks is appropriate. """ ColorSorter.schedule_surface(color, pos, radius, tm, nm) def drawsurface_wireframe(color, pos, radius, tm, nm): glPolygonMode(GL_FRONT, GL_LINE) glPolygonMode(GL_BACK, GL_LINE) glDisable(GL_LIGHTING) glDisable(GL_CULL_FACE) try: drawsurface(color, pos, radius, tm, nm) except: debug.print_compact_traceback("bug, ignored: ") glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glPolygonMode(GL_FRONT, GL_FILL) glPolygonMode(GL_BACK, GL_FILL) return def drawline(color, endpt1, endpt2, dashEnabled = False, stipleFactor = 1, width = 1, isSmooth = False): """ Draw a line from endpt1 to endpt2 in the given color. Actually, schedule it for rendering whenever ColorSorter thinks is appropriate. @param endpt1: First endpoint. @type endpt1: point @param endpt2: Second endpoint. @type endpt2: point @param dashEnabled: If dashEnabled is True, it will be dashed. @type dashEnabled: boolean @param stipleFactor: The stiple factor. @param stipleFactor: int @param width: The line width in pixels. The default is 1. @type width: int or float @param isSmooth: Enables GL_LINE_SMOOTH. The default is False. @type isSmooth: boolean @note: Whether the line is antialiased is determined by GL state variables which are not set in this function. @warning: Some callers pass dashEnabled as a positional argument rather than a named argument. """ ColorSorter.schedule_line(color, endpt1, endpt2, dashEnabled, stipleFactor, width, isSmooth) def drawtriangle_strip(color, triangles, normals, colors): ColorSorter.schedule_triangle_strip(color, triangles, normals, colors) def drawTag(color, basePoint, endPoint, pointSize = 20.0): """ Draw a tag (or a 'flag') as a line ending with a circle (like a balloon with a string). Note: The word 'Flag' is intentionally not used in the method nameto avoid potential confusion with a boolean flag. @param color: color of the tag @type color: A @param basePoint: The base point of the tag @type basePoint: V @param endPoint: The end point of the tag @type endPoint: V @param pointSize: The pointSize of the point to be drawin at the <endPoint> @type pointSize: float @see: GraphicsMode._drawTags where it is called (an example) """ drawline(color, basePoint, endPoint) drawPoint(color, endPoint, pointSize = 20.0) def draw3DFlag(glpane, color, basePoint, cylRadius, cylHeight, direction = None, opacity = 1.0): """ Draw a 3D flag with its base as a 'cylinder' and the head as a sphere. @param glpane: The GLPane object @type glpane: B{GLPane} @param color: color of the tag @type color: A @param basePoint: The base point of the tag @type basePoint: V @param cylRadius: Radius of the base cylinder of the flag @type cylRadius: float @param cylHeight: Height of the base cylinder of the flag @type clyHeight: float @param direction: direction in which to draw the 3D flag. If this is not spcified, it draws the flag using glpane.up @type direction: V (or None) @param opacity: Flag opacity (a value bet 0.0 to 1.0) @type opacity: float """ if direction is None: direction = glpane.up scale = glpane.scale height = cylHeight endPoint = basePoint + direction*height sphereRadius = cylHeight*0.7 sphereCenter = endPoint + direction*0.8*sphereRadius SPHERE_DRAWLEVEL = 2 drawcylinder(color, basePoint, endPoint, cylRadius, capped = True, opacity = opacity) drawsphere(color, sphereCenter, sphereRadius, SPHERE_DRAWLEVEL, opacity = opacity) return # end
NanoCAD-master
cad/src/graphics/drawing/CS_draw_primitives.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ drawing_constants.py - constants and helpers for graphics.drawing package @author: Russ, plus others if the code that belongs here is ever moved here @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: 090304 bruce split out of drawing_globals to avoid import cycles TODO: some geometric variables (but not display lists!) stored into drawing_globals by external code (mostly setup_draw) should instead be defined here. """ # Common constants and helpers for DrawingSet, TransformControl, et al. # Russ 080915: Support for lazily updating drawing caches, namely a change # timestamp. Rather than recording a time per se, an event counter is used. NO_EVENT_YET = 0 _event_counter = NO_EVENT_YET def eventStamp(): global _event_counter _event_counter += 1 return _event_counter def eventNow(): # not used return _event_counter # end
NanoCAD-master
cad/src/graphics/drawing/drawing_constants.py
# Copyright 2005-2007 Nanorex, Inc. See LICENSE file for details. """ draw_bond_vanes.py -- part of the drawing code for higher-order bonds -- represent pi orbitals as "vanes". @author: bruce @version: $Id$ @copyright: 2005-2007 Nanorex, Inc. See LICENSE file for details. """ import math from Numeric import dot from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import glDisable from OpenGL.GL import GL_LIGHT_MODEL_TWO_SIDE from OpenGL.GL import GL_TRUE from OpenGL.GL import glLightModelfv from OpenGL.GL import GL_TRIANGLE_STRIP from OpenGL.GL import glBegin from OpenGL.GL import glNormal3fv from OpenGL.GL import glVertex3fv from OpenGL.GL import glEnd from OpenGL.GL import GL_QUADS from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_LINES from OpenGL.GL import glColor3fv from OpenGL.GL import GL_LINE_STRIP from OpenGL.GL import glEnable from OpenGL.GL import GL_FALSE from geometry.VQT import cross, vlen, norm import foundation.env as env from graphics.drawing.gl_lighting import apply_material from utilities.constants import white from utilities.prefs_constants import pibondStyle_prefs_key # permissible twist of one vane segment (5 degrees -- just a guess) MAXTWIST = 5 * math.pi / 180 def draw_bond_vanes(bond, glpane, sigmabond_cyl_radius, col): """ Given a bond with some pi orbital occupancy (i.e. not a single bond), draw some "vanes" representing the pi orbitals. DON'T use glpane for .out and .up when arbitrary choices are needed -- use coords derived from model-space out and up. """ del glpane pi_info = bond.get_pi_info() if pi_info is not None: # vectors are in bond's coordsys ((a1py, a1pz), (a2py, a2pz), ord_pi_y, ord_pi_z) = pi_info rad = sigmabond_cyl_radius if ord_pi_y: #k does this mean pi_vectors retval order is wrong? draw_vane( bond, a1py, a2py, ord_pi_y, rad, col) pass if ord_pi_z: # this only happens for triple or carbomeric bonds draw_vane( bond, a1pz, a2pz, ord_pi_z, rad, col) return def draw_vane( bond, a1p, a2p, ord_pi, rad, col ): """ Draw a vane (extending on two opposite sides of the bond axis) [#doc more]; use ord_pi to determine how intense it is (not yet sure how, maybe by mixing in bgcolor??); a1p and a2p should be unit vectors perp to bond and no more than 90 degrees apart when seen along it; they should be in the bond's coordinate system. rad is inner radius of vanes, typically the cylinder radius for the sigma bond graphic. If col is not boolean false, use it as the vane color; otherwise, use a constant color which might be influenced by the pi orbital occupancy. """ from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_True, Choice_boolean_False ## twisted = debug_pref('pi vanes/ribbons', Choice_boolean_False) # one of ['multicyl','vane','ribbon'] pi_bond_style = env.prefs[ pibondStyle_prefs_key] twisted = (pi_bond_style == 'ribbon') poles = debug_pref('pi vanes/poles', Choice_boolean_True) draw_outer_edges = debug_pref('pi vanes/draw edges', Choice_boolean_True) #bruce 050730 new feature, so that edge-on vanes are still visible draw_normals = debug_pref('pi vanes/draw normals', Choice_boolean_False) print_vane_params = debug_pref('pi vanes/print params', Choice_boolean_False) if print_vane_params: print "draw vane",a1p,vlen(a1p),a2p,vlen(a2p),ord_pi if twisted: d12 = dot(a1p, a2p) ## assert d12 >= 0.0 if d12 < 0.0: d12 = 0.0 if d12 > 1.0: d12 = 1.0 twist = math.acos(d12) # in radians # this is numerically inaccurate (since d12 is) near d12 == 1.0, but # that's ok, since it's only compared to threshholds (by ceil()) # which correspond to d12 values not near 1.0. # (#e btw, we could optim the common case (ntwists == 1) by # inverting this comparison to get the equivalent threshhold for # d12.) maxtwist = MAXTWIST # debug_pref doesn't yet have a PrefsType for this # number of segments needed, to limit each segment's twist to MAXTWIST ntwists = max(1, int( math.ceil( twist / maxtwist ) )) pass if col: color = col else: #bruce 050804: initial test of bond color prefs; inadequate in several # ways ###@@@ from foundation.preferences import prefs_context prefs = prefs_context() from utilities.prefs_constants import bondVaneColor_prefs_key #k I hope this color tuple of floats is in the correct prefs format color = prefs.get(bondVaneColor_prefs_key) # protect following code from color being None (which causes bus error, # maybe in PyOpenGL) assert len(color) == 3 ###@@@ it would be much faster to update this pref (or almost any # graphics color pref) if the OpenGL command to set the color was in its # own display list, redefined when the redraw starts, and called from # inside every other display list that needs it. Then when you changed # it, gl_update would be enough -- the chunk display lists would not # need to be remade. ###@@@ problems include: # - being fast enough # + dflt should be specified in just one place, and earlier than in this # place, so it can show up in prefs ui before this runs (in fact, even # earlier than when this module is first imported, which might be only # when needed), # - existing prefs don't have all the color vars needed (eg no # toolong-highlighted color) # - being able to track them only when finally used, not when pulled # into convenience vars before final use -- this might even be an # issue if we precompute a formula from a color-pref, but only count # it as used if that result is used. (we could decide to track the # formula res as a separate thing, i suppose) ## a1pos = bond.atom1.posn() ## a2pos = bond.atom2.posn() a1pos, c1, center, c2, a2pos, toolong = bond.geom if not toolong: c1 = c2 = center # don't know if needed x_axis = a2pos - a1pos # from 1 to 2.5, with 1 moved out to shrink width according to ord_pi width = 1.5 * ord_pi inner, outer = 2.5 - width, 2.5 radius_pairs = [(outer, inner, outer), (-inner, -outer, -outer)] # the order within each pair matters, since it affects the polys drawn # below being CW or CCW! but for purposes of edges, we also have to # know which one is *really* outer... thus the third elt (edge_outer) # of the tuple. # OpenGL code #e could optim this to use Numeric calcs and OpenGL vertex array, with # vertex normals and smooth shading, maybe even color ramp of some kind... #e want polygon outlines? #e want a 1d texture to emphasize the vane's ribbonness & help show ord_pi? glDisable(GL_CULL_FACE) #bruce 051215 use apply_material(color) instead of glMaterialfv, partly to # prevent bug of passing 3-tuple to glMaterialfv, partly to make the vanes # appear specular, partly to thereby fix bug 1216 (which was probably caused # by not setting specular color here, thus letting it remain from whatever # happened to be drawn just before). If we decide vanes should *not* appear # specular, we have to actively turn off specular color here rather than # ignoring the issue. One way would be to create and use some new # functionality like apply_material(color, specular=False). apply_material(color) # gl args partly guessed #e should add specularity, shininess... ## glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE) # For vane lighting to be correct, two-sided polygon lighting is # required, and every polygon's vertex winding order (CCW) has to match # its normal vector, as both are produced by the following code. This # means that any changes to the orders of lists of vertices or vectors # in this code have to be considered carefully. But it's ok if a1p and # a2p are negated (fortunately, since calling code arbitrarily negates # them), since this reverses the poly scan directions in two ways at # once (e.g. via pvec and perpvec in the quads case below). (For ribbon # option, it's only ok if they're negated together; for quads case, # independent negation is ok. I'm pretty sure calling code only negates # them together.) [bruce 050725] for outer, inner, edge_outer in radius_pairs: normals = [] edgeverts = [] if twisted: glBegin(GL_TRIANGLE_STRIP) for i in range(1+ntwists): t = float(i) / ntwists # 0.0 to 1.0 # one minus t (python syntax doesn't let me name it just 1mt) _1mt = 1.0 - t #e could optimize, not sure it matters axispos = _1mt * a1pos + t * a2pos # let it get smaller in the middle for large twist (rather than # using angles in calc) pvec = _1mt * a1p + t * a2p # (rationale: shows weakness of bond. real reason: programmer is # in a hurry.) #e btw, it might be better to show twist by mismatch of # larger rectangular vanes, in the middle; and it's faster # to draw. # Could also "* ord_pi" rather than using color, if we worked # out proper min radius. ## pvec *= (rad * 2.5) perpvec = norm(cross(x_axis, pvec)) # test shows this is needed not only for smoothness, but to make # the lighting work at all glNormal3fv( perpvec) outervert = axispos + pvec * rad * outer innervert = axispos + pvec * rad * inner glVertex3fv( outervert) ## not needed, since the same normal as above ## glNormal3fv( perpvec) glVertex3fv( innervert) #e color? want to smooth-shade it using atom colors, or the # blue/gray for bond order, gray in center? if draw_normals: normals.append(( axispos + pvec * rad * edge_outer, perpvec )) if draw_outer_edges: edgeverts.append( axispos + pvec * rad * edge_outer ) glEnd() else: glBegin(GL_QUADS) for axispos, axispos_c, pvec, normalfactor in \ [(a1pos,c1,a1p,-1), (a2pos,c2,a2p,1)]: perpvec = norm(cross(x_axis, pvec)) * normalfactor glNormal3fv( perpvec) glVertex3fv( axispos + pvec * rad * inner) glVertex3fv( axispos + pvec * rad * outer) glVertex3fv( axispos_c + pvec * rad * outer) # This (axispos_c + pvec * rad * outer) would be the corner # we connect by a line, even when not draw_outer_edges, if # outer == edge_outer -- but it might or might not be. glVertex3fv( axispos_c + pvec * rad * inner) if draw_normals: normals.append(( axispos/2.0 + axispos_c/2.0 + pvec * rad * edge_outer, perpvec )) if draw_outer_edges: # Kluge to reverse order of first loop body but not second. edgeverts.reverse() edgeverts.append( axispos_c + pvec * rad * edge_outer) edgeverts.append( axispos + pvec * rad * edge_outer) else: # At least connect the halves of each vane, so that twist # doesn't make them look like 2 vanes. edgeverts.append( axispos_c + pvec * rad * edge_outer) glEnd() ## glBegin(GL_LINES) ## glColor3fv(color) ## for axispos, axispos_c, pvec in [(a1pos,c1,a1p), (a2pos,c2,a2p)]: ## glVertex3fv( axispos_c + pvec * rad * outer) ## glEnd() glDisable(GL_LIGHTING) # for lines... don't know if this matters if poles: glBegin(GL_LINES) glColor3fv(color) for axispos, pvec in [(a1pos,a1p), (a2pos,a2p)]: glVertex3fv( axispos + pvec * rad * outer) glVertex3fv( axispos + pvec * rad * -outer) glEnd() if normals: glBegin(GL_LINES) glColor3fv(white) for base, vec in normals: glVertex3fv(base) glVertex3fv(base + vec) glEnd() if edgeverts: glBegin(GL_LINE_STRIP) glColor3fv(color) for vert in edgeverts: glVertex3fv(vert) glEnd() glEnable(GL_LIGHTING) glEnable(GL_CULL_FACE) glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE) return # end
NanoCAD-master
cad/src/graphics/drawing/draw_bond_vanes.py
# Copyright 2005-2009 Nanorex, Inc. See LICENSE file for details. """ graphics_card_info.py - def get_gl_info_string, to query OpenGL extensions @version: $Id$ @copyright: 2005-2009 Nanorex, Inc. See LICENSE file for details. History: 051129 Brad G developed (in drawer.py) (since then, perhaps, minor improvements by various developers) 080519 Russ split up drawer.py; this function ended up in gl_lighting.py 090314 Bruce moved it into its own file """ from OpenGL.GL import glAreTexturesResident from OpenGL.GL import glBegin from OpenGL.GL import glBindTexture from OpenGL.GL import glDeleteTextures from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import glEnd from OpenGL.GL import GL_EXTENSIONS from OpenGL.GL import glFinish from OpenGL.GL import glGenTextures from OpenGL.GL import glGetInteger from OpenGL.GL import glGetString from OpenGL.GL import GL_QUADS from OpenGL.GL import GL_RENDERER from OpenGL.GL import GL_RGBA from OpenGL.GL import glTexCoord2f from OpenGL.GL import GL_TEXTURE_2D from OpenGL.GL import GL_UNSIGNED_BYTE from OpenGL.GL import GL_VENDOR from OpenGL.GL import GL_VERSION from OpenGL.GL import glVertex2f from OpenGL.GLU import gluBuild2DMipmaps from utilities.debug_prefs import debug_pref, Choice_boolean_False from utilities import debug_flags from utilities.debug import print_compact_traceback # == def get_gl_info_string(glpane): # grantham 20051129 """ Return a string containing some useful information about the OpenGL implementation. Use the GL context from the given QGLWidget glpane (by calling glpane.makeCurrent()). """ glpane.makeCurrent() #bruce 070308 added glpane arg and makeCurrent call gl_info_string = '' gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR) gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION) gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER) gl_extensions = glGetString(GL_EXTENSIONS) gl_extensions = gl_extensions.strip() gl_extensions = gl_extensions.replace(" ", "\n* ") gl_info_string += 'GL_EXTENSIONS : \n* %s\n' % gl_extensions if debug_pref("Graphics Card Info: call glAreTexturesResident?", Choice_boolean_False): # Give a practical indication of how much video memory is available. # Should also do this with VBOs. # I'm pretty sure this code is right, but PyOpenGL seg faults in # glAreTexturesResident, so it's disabled until I can figure that # out. [grantham] [bruce 070308 added the debug_pref] all_tex_in = True tex_bytes = '\0' * (512 * 512 * 4) tex_names = [] tex_count = 0 tex_names = glGenTextures(1024) glEnable(GL_TEXTURE_2D) while all_tex_in: glBindTexture(GL_TEXTURE_2D, tex_names[tex_count]) gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA, GL_UNSIGNED_BYTE, tex_bytes) tex_count += 1 glTexCoord2f(0.0, 0.0) glBegin(GL_QUADS) glVertex2f(0.0, 0.0) glVertex2f(1.0, 0.0) glVertex2f(1.0, 1.0) glVertex2f(0.0, 1.0) glEnd() glFinish() residences = glAreTexturesResident(tex_names[:tex_count]) all_tex_in = reduce(lambda a,b: a and b, residences) # bruce 070308 sees this exception from this line: # TypeError: reduce() arg 2 must support iteration glDisable(GL_TEXTURE_2D) glDeleteTextures(tex_names) gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \ % tex_count pass if True: ## or could be a debug_pref("Graphics Card Info: get all GL_MAX symbols?") #bruce 090314 new feature import OpenGL.GL symbols = [x for x in dir(OpenGL.GL) if x.startswith('GL_MAX_')] symbols.sort() gl_info_string += '\n' for symbol in symbols: try: numeric_symbol = getattr(OpenGL.GL, symbol) intval = glGetInteger(numeric_symbol) except: # this happens to most symbols, not sure why if debug_flags.atom_debug: print_compact_traceback( "%s = ??: " % symbol ) # overkill, only the exception itself matters # typical output (on Bruce's MacBookPro, 090314): ## GL_MAX_4D_TEXTURE_SIZE_SGIS = ??: ## <type 'exceptions.KeyError'>: ## ('Unknown specifier GL_MAX_4D_TEXTURE_SIZE_SGIS (33080)', ## 'Failure in cConverter <OpenGL.converters.SizedOutput object at 0x1457fab0>', ## [GL_MAX_4D_TEXTURE_SIZE_SGIS], 1, <OpenGL.wrapper.glGetIntegerv object at 0x1458aa30>) ## [graphics_card_info.py:122] [wrapper.py:676] [converters.py:195] [converters.py:234] pass pass ## gl_info_string += "%s = ??\n" % symbol else: gl_info_string += "%s = %r\n" % (symbol, intval) continue pass return gl_info_string # end
NanoCAD-master
cad/src/graphics/drawing/graphics_card_info.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ gl_GLE.py - Details of loading the GLE functions. @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: russ 080523: Factored out duplicate code from CS_draw_primitives.py, CS_workers.py, and drawers.py . """ try: from OpenGL.GLE import glePolyCone, gleGetNumSides, gleSetNumSides except: print "GLE module can't be imported. Now trying _GLE" from OpenGL._GLE import glePolyCone, gleGetNumSides, gleSetNumSides # Check if the gleGet/SetNumSides function is working on this install, and if # not, patch it to call gleGet/SetNumSlices. Checking method is as recommended # in an OpenGL exception reported by Brian [070622]: # OpenGL.error.NullFunctionError: Attempt to call an # undefined function gleGetNumSides, check for # bool(gleGetNumSides) before calling # The underlying cause of this (described by Brian) is that the computer's # OpenGL has the older gleGetNumSlices (so it supports the functionality), but # PyOpenGL binds (only) to the newer gleGetNumSides. I [bruce 070629] think # Brian said this is only an issue on Macs. if not bool(gleGetNumSides): # russ 080522: Replaced no-op functions with a patch. print "fyi: Patching gleGetNumSides to call gleGetNumSlices instead." from graphics.drawing.gleNumSides_patch import gleGetNumSides from graphics.drawing.gleNumSides_patch import gleSetNumSides # russ 081227: The no-ops may still be needed, e.g. on Fedora 10 Linux. try: gleGetNumSides() except: print "fyi: Neither gleGetNumSides nor gleGetNumSlices is supported." print "fyi: No-ops will be used for gleGetNumSides and gleSetNumSides." gleGetNumSides = int gleSetNumSides = int pass pass
NanoCAD-master
cad/src/graphics/drawing/gl_GLE.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ setup_draw.py - The function to allocate and compile our standard display lists into the current GL context, and initialize the globals that hold their opengl names. NOTE/TODO: this needs to be merged with drawing_globals, and refactored, since it's specific to a "GL resource context" (of which we only use one so far, since all our GLPanes share display lists). @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originated by Josh in drawer.py Various developers extended it since then. At some point Bruce partly cleaned up the use of display lists. 071030 bruce split some functions and globals into draw_grid_lines.py and removed some obsolete functions. 080519 russ pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py """ # the imports from math vs. Numeric are as discovered in existing code # as of 2007/06/25. It's not clear why acos is coming from math... from Numeric import sin, cos, pi from OpenGL.GL import GL_ARRAY_BUFFER_ARB from OpenGL.GL import glBegin from OpenGL.GL import GL_COMPILE from OpenGL.GL import glDisable from OpenGL.GL import GL_ELEMENT_ARRAY_BUFFER_ARB from OpenGL.GL import glEnable from OpenGL.GL import glEnd from OpenGL.GL import glEndList from OpenGL.GL import GL_EXTENSIONS from OpenGL.GL import glGenLists from OpenGL.GL import glGetString from OpenGL.GL import GL_LINE_LOOP from OpenGL.GL import GL_LINES from OpenGL.GL import GL_LINE_SMOOTH from OpenGL.GL import GL_LINE_STRIP from OpenGL.GL import glNewList from OpenGL.GL import glNormal3fv from OpenGL.GL import GL_POLYGON from OpenGL.GL import GL_QUADS from OpenGL.GL import GL_QUAD_STRIP from OpenGL.GL import GL_STATIC_DRAW from OpenGL.GL import GL_TRIANGLES from OpenGL.GL import GL_TRIANGLE_STRIP from OpenGL.GL import GL_UNSIGNED_BYTE from OpenGL.GL import GL_UNSIGNED_SHORT from OpenGL.GL import glVertex from OpenGL.GL import glVertex3f from OpenGL.GL import glVertex3fv from geometry.VQT import norm, V, A import graphics.drawing.drawing_globals as drawing_globals from graphics.drawing.shape_vertices import getSphereTriStrips from graphics.drawing.shape_vertices import getSphereTriangles from graphics.drawing.shape_vertices import indexVerts from graphics.drawing.gl_buffers import GLBufferObject import numpy _NUM_SPHERE_SIZES = 3 def setup_drawer(): """ Set up the usual constant display lists in the current OpenGL context. WARNING: THIS IS ONLY CORRECT IF ONLY ONE GL CONTEXT CONTAINS DISPLAY LISTS -- or more precisely, only the GL context this has last been called in (or one which shares its display lists) will work properly with the routines in drawer.py, since the allocated display list names are stored in globals set by this function, but in general those names might differ if this was called in different GL contexts. """ spherelistbase = glGenLists(_NUM_SPHERE_SIZES) sphereList = [] for i in range(_NUM_SPHERE_SIZES): sphereList += [spherelistbase+i] glNewList(sphereList[i], GL_COMPILE) glBegin(GL_TRIANGLE_STRIP) # GL_LINE_LOOP to see edges stripVerts = getSphereTriStrips(i) for vertNorm in stripVerts: glNormal3fv(vertNorm) glVertex3fv(vertNorm) continue glEnd() glEndList() continue drawing_globals.sphereList = sphereList # Sphere triangle-strip vertices for each level of detail. # (Cache and re-use the work of making them.) # Can use in converter-wrappered calls like glVertexPointerfv, # but the python arrays are re-copied to C each time. sphereArrays = [] for i in range(_NUM_SPHERE_SIZES): sphereArrays += [getSphereTriStrips(i)] continue drawing_globals.sphereArrays = sphereArrays # Sphere glDrawArrays triangle-strip vertices for C calls. # (Cache and re-use the work of converting a C version.) # Used in thinly-wrappered calls like glVertexPointer. sphereCArrays = [] for i in range(_NUM_SPHERE_SIZES): CArray = numpy.array(sphereArrays[i], dtype = numpy.float32) sphereCArrays += [CArray] continue drawing_globals.sphereCArrays = sphereCArrays # Sphere indexed vertices. # (Cache and re-use the work of making the indexes.) # Can use in converter-wrappered calls like glDrawElementsui, # but the python arrays are re-copied to C each time. sphereElements = [] # Pairs of lists (index, verts) . for i in range(_NUM_SPHERE_SIZES): sphereElements += [indexVerts(sphereArrays[i], .0001)] continue drawing_globals.sphereElements = sphereElements # Sphere glDrawElements index and vertex arrays for C calls. sphereCIndexTypes = [] # numpy index unsigned types. sphereGLIndexTypes = [] # GL index types for drawElements. sphereCElements = [] # Pairs of numpy arrays (Cindex, Cverts) . for i in range(_NUM_SPHERE_SIZES): (index, verts) = sphereElements[i] if len(index) < 256: Ctype = numpy.uint8 GLtype = GL_UNSIGNED_BYTE else: Ctype = numpy.uint16 GLtype = GL_UNSIGNED_SHORT pass sphereCIndexTypes += [Ctype] sphereGLIndexTypes += [GLtype] sphereCIndex = numpy.array(index, dtype = Ctype) sphereCVerts = numpy.array(verts, dtype = numpy.float32) sphereCElements += [(sphereCIndex, sphereCVerts)] continue drawing_globals.sphereCIndexTypes = sphereCIndexTypes drawing_globals.sphereGLIndexTypes = sphereGLIndexTypes drawing_globals.sphereCElements = sphereCElements if glGetString(GL_EXTENSIONS).find("GL_ARB_vertex_buffer_object") >= 0: # A GLBufferObject version for glDrawArrays. sphereArrayVBOs = [] for i in range(_NUM_SPHERE_SIZES): vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB, sphereCArrays[i], GL_STATIC_DRAW) sphereArrayVBOs += [vbo] continue drawing_globals.sphereArrayVBOs = sphereArrayVBOs # A GLBufferObject version for glDrawElements indexed verts. sphereElementVBOs = [] # Pairs of (IBO, VBO) for i in range(_NUM_SPHERE_SIZES): ibo = GLBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, sphereCElements[i][0], GL_STATIC_DRAW) vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB, sphereCElements[i][1], GL_STATIC_DRAW) sphereElementVBOs += [(ibo, vbo)] continue drawing_globals.sphereElementVBOs = sphereElementVBOs ibo.unbind() vbo.unbind() pass #bruce 060415 drawing_globals.wiresphere1list = wiresphere1list = glGenLists(1) glNewList(wiresphere1list, GL_COMPILE) didlines = {} # don't draw each triangle edge more than once def shoulddoline(v1,v2): # make sure not list (unhashable) or Numeric array (bug in __eq__) v1 = tuple(v1) v2 = tuple(v2) if (v1,v2) not in didlines: didlines[(v1,v2)] = didlines[(v2,v1)] = None return True return False def doline(v1,v2): if shoulddoline(v1,v2): glVertex3fv(v1) glVertex3fv(v2) return glBegin(GL_LINES) ocdec = getSphereTriangles(1) for tri in ocdec: #e Could probably optim this more, e.g. using a vertex array or VBO or # maybe GL_LINE_STRIP. doline(tri[0], tri[1]) doline(tri[1], tri[2]) doline(tri[2], tri[0]) glEnd() glEndList() drawing_globals.CylList = CylList = glGenLists(1) glNewList(CylList, GL_COMPILE) glBegin(GL_TRIANGLE_STRIP) for (vtop, ntop, vbot, nbot) in drawing_globals.cylinderEdges: glNormal3fv(nbot) glVertex3fv(vbot) glNormal3fv(ntop) glVertex3fv(vtop) glEnd() glEndList() drawing_globals.CapList = CapList = glGenLists(1) glNewList(CapList, GL_COMPILE) glNormal3fv(drawing_globals.cap0n) glBegin(GL_POLYGON) for p in drawing_globals.drum0: glVertex3fv(p) glEnd() glNormal3fv(drawing_globals.cap1n) glBegin(GL_POLYGON) #bruce 060609 fix "ragged edge" bug in this endcap: drum1 -> drum2 for p in drawing_globals.drum2: glVertex3fv(p) glEnd() glEndList() drawing_globals.diamondGridList = diamondGridList = glGenLists(1) glNewList(diamondGridList, GL_COMPILE) glBegin(GL_LINES) for p in drawing_globals.digrid: glVertex(p[0]) glVertex(p[1]) glEnd() glEndList() drawing_globals.lonsGridList = lonsGridList = glGenLists(1) glNewList(lonsGridList, GL_COMPILE) glBegin(GL_LINES) for p in drawing_globals.lonsEdges: glVertex(p[0]) glVertex(p[1]) glEnd() glEndList() drawing_globals.CubeList = CubeList = glGenLists(1) glNewList(CubeList, GL_COMPILE) glBegin(GL_QUAD_STRIP) # note: CubeList has only 4 faces of the cube; only suitable for use in # wireframes; see also solidCubeList [bruce 051215 comment reporting # grantham 20051213 observation] glVertex((-1,-1,-1)) glVertex(( 1,-1,-1)) glVertex((-1, 1,-1)) glVertex(( 1, 1,-1)) glVertex((-1, 1, 1)) glVertex(( 1, 1, 1)) glVertex((-1,-1, 1)) glVertex(( 1,-1, 1)) glVertex((-1,-1,-1)) glVertex(( 1,-1,-1)) glEnd() glEndList() drawing_globals.solidCubeList = solidCubeList = glGenLists(1) glNewList(solidCubeList, GL_COMPILE) glBegin(GL_QUADS) for i in xrange(len(drawing_globals.cubeIndices)): avenormals = V(0,0,0) #bruce 060302 fixed normals for flat shading for j in xrange(4) : nTuple = tuple( drawing_globals.cubeNormals[drawing_globals.cubeIndices[i][j]]) avenormals += A(nTuple) avenormals = norm(avenormals) for j in xrange(4) : vTuple = tuple( drawing_globals.cubeVertices[drawing_globals.cubeIndices[i][j]]) #bruce 060302 made size compatible with glut.glutSolidCube(1.0) vTuple = A(vTuple) * 0.5 glNormal3fv(avenormals) glVertex3fv(vTuple) glEnd() glEndList() drawing_globals.rotSignList = rotSignList = glGenLists(1) glNewList(rotSignList, GL_COMPILE) glBegin(GL_LINE_STRIP) for ii in xrange(len(drawing_globals.rotS0n)): glVertex3fv(tuple(drawing_globals.rotS0n[ii])) glEnd() glBegin(GL_LINE_STRIP) for ii in xrange(len(drawing_globals.rotS1n)): glVertex3fv(tuple(drawing_globals.rotS1n[ii])) glEnd() glBegin(GL_TRIANGLES) for v in drawing_globals.arrow0Vertices + drawing_globals.arrow1Vertices: glVertex3f(v[0], v[1], v[2]) glEnd() glEndList() drawing_globals.linearArrowList = linearArrowList = glGenLists(1) glNewList(linearArrowList, GL_COMPILE) glBegin(GL_TRIANGLES) for v in drawing_globals.linearArrowVertices: glVertex3f(v[0], v[1], v[2]) glEnd() glEndList() drawing_globals.linearLineList = linearLineList = glGenLists(1) glNewList(linearLineList, GL_COMPILE) glEnable(GL_LINE_SMOOTH) glBegin(GL_LINES) glVertex3f(0.0, 0.0, -drawing_globals.halfHeight) glVertex3f(0.0, 0.0, drawing_globals.halfHeight) glEnd() glDisable(GL_LINE_SMOOTH) glEndList() drawing_globals.circleList = circleList = glGenLists(1) glNewList(circleList, GL_COMPILE) glBegin(GL_LINE_LOOP) for ii in range(60): x = cos(ii*2.0*pi/60) y = sin(ii*2.0*pi/60) glVertex3f(x, y, 0.0) glEnd() glEndList() # piotr 080405 drawing_globals.filledCircleList = filledCircleList = glGenLists(1) glNewList(filledCircleList, GL_COMPILE) glBegin(GL_POLYGON) for ii in range(60): x = cos(ii*2.0*pi/60) y = sin(ii*2.0*pi/60) glVertex3f(x, y, 0.0) glEnd() glEndList() drawing_globals.lineCubeList = lineCubeList = glGenLists(1) glNewList(lineCubeList, GL_COMPILE) glBegin(GL_LINES) cvIndices = [0,1, 2,3, 4,5, 6,7, 0,3, 1,2, 5,6, 4,7, 0,4, 1,5, 2,6, 3,7] for i in cvIndices: glVertex3fv(tuple(drawing_globals.cubeVertices[i])) glEnd() glEndList() #initTexture('C:\\Huaicai\\atom\\temp\\newSample.png', 128,128) return # from setup_drawer
NanoCAD-master
cad/src/graphics/drawing/setup_draw.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ glprefs.py - class GLPrefs encapsulates prefs affecting all Chunk display lists @author: Brad G, Bruce, Russ @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: 080519 russ pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py. 090303 bruce refactored this and related code, pulling in shader prefs. """ from utilities.prefs_constants import material_specular_highlights_prefs_key from utilities.prefs_constants import material_specular_shininess_prefs_key from utilities.prefs_constants import material_specular_finish_prefs_key from utilities.prefs_constants import material_specular_brightness_prefs_key from utilities.prefs_constants import selectionColorStyle_prefs_key from utilities.prefs_constants import selectionColor_prefs_key from utilities.prefs_constants import haloWidth_prefs_key from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice from utilities.debug_prefs import Choice_boolean_False from utilities.debug_prefs import Choice_boolean_True import foundation.env as env from graphics.drawing.c_renderer import quux_module_import_succeeded # == _choices = [Choice_boolean_False, Choice_boolean_True] # == class GLPrefs: """ This has not yet been split into its abstract and concrete classes, but is best described by specifying both aspects: Abstract: instances contain cached values of preferences or other settings which affect overall appearance of a GLPane, or content of most or all of its Chunks' display lists. There are public attributes for the prefs values, and public methods for setting up debug_prefs and updating cached prefs values. The update method should be called near the beginning of paintGL in order that the other methods and attributes have up to date values. Chunks can extract a change indicator (by calling materialprefs_summary) which combines all prefs values in which any changes need to invalidate all Chunk display lists. Concrete: the prefs/settings values are derived from specific env.prefs keys and/or debug_prefs. Only one instance is needed, and any number of GLPanes (or other "graphics environments") can use it (in current code, all GLPane_minimals and nothing else uses it). """ # grantham 20051118; revised by bruce 051126, 090303 # review: rename?? can't rename module to GLPrefs.py, might confuse svn on Macs. # gl_material_and_shader_prefs?? what is the general kind of prefs that belong here? # note: apply_material should probably be moved here (and perhaps made into # a method of this class and then of glpane). See comment near it for why. # [bruce 090304 comment] # == # class constants and initial values of instance variables # Prefs related to experimental native C renderer (quux module in # cad/src/experimental/pyrex-opengl) # # [note: as of 090114, this hasn't been maintained for a long time, # but it might still mostly work, so we'll keep it around for now # as potentially useful example code] use_c_renderer = use_c_renderer_default = False use_c_renderer_prefs_key = "use_c_renderer_rev2" # ColorSorter control prefs (some) #russ 080403: Added drawing variant selection for unbatched spheres. use_drawing_variant = use_drawing_variant_default = 1 # DrawArrays from CPU RAM. use_drawing_variant_prefs_key = "use_drawing_variant" #russ 080819: Added. _use_sphere_shaders = use_sphere_shaders_default = True #bruce 090225 revised use_sphere_shaders_prefs_key = "v1.2/GLPane: use_sphere_shaders" #russ 090116: Added. _use_cylinder_shaders = use_cylinder_shaders_default = True #bruce 090303 revised use_cylinder_shaders_prefs_key = "v1.2/GLPane: use_cylinder_shaders" #russ 090223: Added. _use_cone_shaders = use_cone_shaders_default = True #bruce 090225 revised use_cone_shaders_prefs_key = "v1.2/GLPane: use_cone_shaders" # Russ 081002: Added. _use_batched_primitive_shaders = use_batched_primitive_shaders_default = True #bruce 090225 revised use_batched_primitive_shaders_prefs_key = "v1.2/GLPane: use_batched_primitive_shaders" # == def __init__(self): self._setup() self.update() return # == setup methods def _setup(self): """ Call this once at startup to make sure the appropriate debug_prefs (if any) and env.prefs default values are defined. If these are all changed into prefs_constants prefs rather than debug_prefs, this function won't be needed. """ self._setup_c_renderer_prefs() # material prefs don't need setup since they're all in prefs_constants # which we import. They don't have class constant default values above # since they are all set in self.update() which this method calls. ## self.override_material_specular = None ## # Set 4-element sequence to override material specular component. ## self.override_shininess = None ## # If exists, overrides shininess. ## self.override_light_specular = None ## # Set to 4-element sequence to override light specular component. self._setup_shader_prefs() return def _setup_c_renderer_prefs(self): # 20060313 grantham Added use_c_renderer debug pref, can # take out when C renderer used by default. # REVIEW: is this still next-session, or does it work fine for same session now? # Guess: works for same-session after today's refactoring (once it works again at all). # So I modified the debug_pref menu text optimistically. [bruce 090304] if quux_module_import_succeeded: self.use_c_renderer = ( debug_pref("GLPane: use native C renderer?", #bruce 090304 revised text _choices[self.use_c_renderer_default], prefs_key = self.use_c_renderer_prefs_key)) #bruce 060323 removed non_debug = True for A7 release, and changed # its prefs_key so developers start over with the default value. return def _setup_shader_prefs(self): # note: as of bruce 090304 these all should work as same-session prefs, # and most of them have been tested that way. self.use_sphere_shaders_pref = debug_pref( "GLPane: use sphere-shaders?", _choices[self.use_sphere_shaders_default], non_debug = True, prefs_key = self.use_sphere_shaders_prefs_key ) self.use_cylinder_shaders_pref = debug_pref( "GLPane: use cylinder-shaders?", _choices[self.use_cylinder_shaders_default], non_debug = True, prefs_key = self.use_cylinder_shaders_prefs_key ) self.use_cone_shaders_pref = debug_pref( "GLPane: use cone-shaders?", _choices[self.use_cone_shaders_default], non_debug = True, prefs_key = self.use_cone_shaders_prefs_key ) self.use_batched_primitive_shaders_pref = debug_pref( "GLPane: use batched primitive shaders?", _choices[ self.use_batched_primitive_shaders_default], non_debug = True, prefs_key = self.use_batched_primitive_shaders_prefs_key ) #russ 080403: Added drawing variant selection for unbatched spheres # (update, bruce 090304: mainly of historical interest or for testing, # but does matter on older machines that can't use shaders; # could be extended to affect other primitives, but hasn't been # as of 090304) variants = [ "0. OpenGL 1.0 - glBegin/glEnd tri-strips vertex-by-vertex.", "1. OpenGL 1.1 - glDrawArrays from CPU RAM.", "2. OpenGL 1.1 - glDrawElements indexed arrays from CPU RAM.", "3. OpenGL 1.5 - glDrawArrays from graphics RAM VBO.", "4. OpenGL 1.5 - glDrawElements, verts in VBO, index in CPU.", "5. OpenGL 1.5 - VBO/IBO buffered glDrawElements.", ] self.use_drawing_variant = debug_pref( "GLPane: drawing method (unbatched spheres)", Choice(names = variants, values = range(len(variants)), defaultValue = self.use_drawing_variant_default), prefs_key = self.use_drawing_variant_prefs_key) return # == def update(self): #bruce 051126, revised 090303 """ Update attributes from current drawing-related prefs stored in prefs db cache. This should be called at the start of each complete redraw, or whenever the user changes these global prefs values (whichever is more convenient). It is ok to call this more than once at those times -- this will be a slight slowdown but cause no other harm. (Current code does this because more than one glpane can share one GLPrefs object, and because of a kluge which requires GLPane itself to update it twice.) (Note: When this is called during redraw, its prefs db accesses (like any others) record those prefs as potentially affecting what should be drawn, so that subsequent changes to those prefs values cause an automatic gl_update.) Using these attributes in drawing code (rather than directly accessing prefs db cache) is desirable for efficiency, since direct access to prefs db cache is a bit slow. (Our drawing code still does that in other places -- those might also benefit from this system, though this will someday be moot when low-level drawing code gets rewritten in C.) """ self._update_c_renderer_prefs() self._update_material_prefs() self._update_shader_prefs() return def _update_c_renderer_prefs(self): self.use_c_renderer = ( quux_module_import_succeeded and env.prefs.get(self.use_c_renderer_prefs_key, self.use_c_renderer_default) ) if self.use_c_renderer: import quux quux.shapeRendererSetMaterialParameters(self.specular_whiteness, self.specular_brightness, self.specular_shininess ) pass return def _update_material_prefs(self): self.enable_specular_highlights = not not env.prefs[ material_specular_highlights_prefs_key] # boolean if self.enable_specular_highlights: self.override_light_specular = None # used in glpane # self.specular_shininess: float; shininess exponent for all # specular highlights self.specular_shininess = float( env.prefs[material_specular_shininess_prefs_key]) # self.specular_whiteness: float; whiteness for all material # specular colors self.specular_whiteness = float( env.prefs[material_specular_finish_prefs_key]) # self.specular_brightness: float; for all material specular colors self.specular_brightness = float( env.prefs[material_specular_brightness_prefs_key]) else: self.override_light_specular = (0.0, 0.0, 0.0, 0.0) # used in glpane # Set these to reasonable values, though these attributes are # presumably never used in this case. Don't access the prefs db in # this case, since that would cause UI prefs changes to do # unnecessary gl_updates. (If we ever add a scenegraph node which # can enable specular highlights but use outside values for these # parameters, then to make it work correctly we'll need to revise # this code.) self.specular_shininess = 20.0 self.specular_whiteness = 1.0 self.specular_brightness = 1.0 pass return def _update_shader_prefs(self): # Russ 080915: Extracted from GLPrefs.update() to break an import cycle. # # bruce 090303 renamed this from updatePrefsVars, refactored it # from a global function to a method of this class, and heavily # revised related code. # implem note: this is slightly faster than directly calling debug_pref # (though that needs to be done the first time, via _setup_shader_prefs); # and as of 090303 the split between this and _setup_shader_prefs is # confined to this module, so if we change some of these to non-debug_prefs # no external code should need to be changed. [bruce 090303 comment] self._use_sphere_shaders = env.prefs.get( self.use_sphere_shaders_prefs_key, self.use_sphere_shaders_default) self._use_cylinder_shaders = env.prefs.get( self.use_cylinder_shaders_prefs_key, self.use_cylinder_shaders_default) self._use_cone_shaders = env.prefs.get( self.use_cone_shaders_prefs_key, self.use_cone_shaders_default) self._use_batched_primitive_shaders = env.prefs.get( self.use_batched_primitive_shaders_prefs_key, self.use_batched_primitive_shaders_default) self.use_drawing_variant = env.prefs.get( self.use_drawing_variant_prefs_key, self.use_drawing_variant_default) return # == def materialprefs_summary(self): #bruce 051126 ### TODO: RENAME; refactor to connect more strongly to apply_material """ Return a Python data object (which can be correctly compared using '==') summarizing our cached pref values which affect the OpenGL output of apply_material. OpenGL display lists whose content includes output from apply_material need to be remade if our output differs from when they were first made. Note that any env.prefs value accessed directly (via env.prefs[key] or debug_pref()) when making a DL needn't be included in our output, since those accesses are usage-tracked and anything making a DL can independently subscribe to changes in them (see begin_tracking_usage). The only prefs values that doesn't work for are the ones cached in self, so only those values need to be included in this method's output. Note also that CSDLs (ColorSortedDisplayLists) may depend on fewer prefs values, since they are likely to use apply_material when drawn rather than when made. So our output may be overkill if used to invalidate them in the same circumstances in which it would invalidate a plain OpenGL DL. @note: only valid if self.update() has been called recently. """ # bruce 090305 rewrote docstring to explain the purpose better. #### todo: optimizations (not urgent except for user experience # when adjusting these prefs on a large model): # # * remove prefs from our output which are not needed according to the # docstring above, as rewritten 090305. # # * if some prefs are only needed here for DLs but not for CSDLs, # revise callers accordingly. (AFAIK no revision in this class itself # makes sense then, unless we need to add a new analgous method to # correspond to a new way of accessing a subset of our prefs values, # for making CSDLs. But AFAIK, our values are used only for *drawing* # CSDL shader primitives, never for *making* them (though they may be # used for making CSDLs using DL primitives rather than shader # primitives), so we're simply not needed in ChunkDrawer.havelist # when it's not using apply_material in any plain DLs. Note that # whether it's doing that or not depends on prefs settings normally # only used inside ColorSorter, so it probably wants to ask # ColorSorter for a "prefs summary" applicable to how it's making # CSDLs at that time. This would always include # self._use_batched_primitive_shaders, and when that's false, # also include the "material prefs" which this method used to only # include.) # # * clients and/or this method should condense the summary tuple # into a single change indicator/counter, by comparing the tuple # to the last one used. Clients can do this better in principle # (if we're shared by several GLPanes which don't always redraw # together). # # * include values in our output only when they matter based on # other values. This is probably true already for the actual # "material prefs". # # Summary: much of what we output is not needed, and needlessly # slows down some prefs changes, but this takes some analysis to fix. # If in doubt, including too much is better since it only slows down # prefs changes, whereas including too little causes bugs of lack of # chunk appearance update when it's required. res = (self.enable_specular_highlights,) if self.enable_specular_highlights: res = res + ( self.specular_shininess, self.specular_whiteness, self.specular_brightness ) res += ( self.use_c_renderer, self.use_drawing_variant, self._use_sphere_shaders, self._use_cylinder_shaders, self._use_cone_shaders, self._use_batched_primitive_shaders, ) # russ 080530: Selection style preference controls select_dl contents. res += (env.prefs[selectionColorStyle_prefs_key],) res += (env.prefs[selectionColor_prefs_key],) res += (env.prefs[haloWidth_prefs_key],) return res # == def sphereShader_desired(self): #bruce 090303 """ Based only on preferences, is it desired to use shaders for spheres in CSDLs? @note: only valid if self.update() has been called recently. This is ensured by current code by calling this via enable_shaders which is called only in configure_enabled_shaders, which is only called after its caller (GLPane in one call of paintGL) has called self.update. @see: drawing_globals.sphereShader_available() """ return self._use_batched_primitive_shaders and self._use_sphere_shaders def cylinderShader_desired(self): #bruce 090303 """ Based only on preferences, is it desired to use shaders for cylinders in CSDLs? @note: only valid if self.update() has been called recently. @see: drawing_globals.cylinderShader_available() """ return self._use_batched_primitive_shaders and self._use_cylinder_shaders def coneShader_desired(self): #bruce 090303 """ Based only on preferences, is it desired to use shaders for cones in CSDLs? @note: only valid if self.update() has been called recently. @see: drawing_globals.coneShader_available() """ # this is intentionally not symmetric with cylinderShader_desired(), # since we want turning off cylinder shader pref to turn off all uses # of the cylinder shader, including cones. return self._use_batched_primitive_shaders and self._use_cylinder_shaders and \ self._use_cone_shaders pass # end of class glprefs # end
NanoCAD-master
cad/src/graphics/drawing/glprefs.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ shape_vertices.py - Geometric constructions of vertex lists used by the drawing functions. This includes vertices for the shapes of primitives that will go into display lists in the setup_drawer function in setup_draw.py . @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Originated by Josh as drawer.py . Various developers extended it since then. Brad G. added ColorSorter features. At some point Bruce partly cleaned up the use of display lists. 071030 bruce split some functions and globals into draw_grid_lines.py and removed some obsolete functions. 080210 russ Split the single display-list into two second-level lists (with and without color) and a set of per-color sublists so selection and hover-highlight can over-ride Chunk base colors. ColorSortedDisplayList is now a class in the parent's displist attr to keep track of all that stuff. 080311 piotr Added a "drawpolycone_multicolor" function for drawing polycone tubes with per-vertex colors (necessary for DNA display style) 080313 russ Added triangle-strip icosa-sphere constructor, "getSphereTriStrips". 080420 piotr Solved highlighting and selection problems for multi-colored objects (e.g. rainbow colored DNA structures). 080519 russ pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py """ # the imports from math vs. Numeric are as discovered in existing code # as of 2007/06/25. It's not clear why acos is coming from math... from math import atan2 from Numeric import sin, cos, sqrt, pi degreesPerRadian = 180.0 / pi from geometry.VQT import norm, vlen, V, Q, A from utilities.constants import DIAMOND_BOND_LENGTH import graphics.drawing.drawing_globals as drawing_globals # REVIEW: probably we should refactor so we don't depend on assignments # into drawing_globals as a side effect of importing this module. # [bruce 081001 comment] def init_icos(): global icosa, icosix # the golden ratio global phi phi = (1.0+sqrt(5.0))/2.0 vert = norm(V(phi,0,1)) a = vert[0] b = vert[1] c = vert[2] # vertices of an icosahedron icosa = ((-a,b,c), (b,c,-a), (b,c,a), (a,b,-c), (-c,-a,b), (-c,a,b), (b,-c,a), (c,a,b), (b,-c,-a), (a,b,c), (c,-a,b), (-a,b,-c)) icosix = ((9, 2, 6), (1, 11, 5), (11, 1, 8), (0, 11, 4), (3, 1, 7), (3, 8, 1), (9, 3, 7), (0, 6, 2), (4, 10, 6), (1, 5, 7), (7, 5, 2), (8, 3, 10), (4, 11, 8), (9, 7, 2), (10, 9, 6), (0, 5, 11), (0, 2, 5), (8, 10, 4), (3, 9, 10), (6, 0, 4)) return init_icos() # generate geodesic spheres by subdividing the faces of an icosahedron # recursively: # /\ /\ # / \ / \ # / \ /____\ # / \ => /\ /\ # / \ / \ / \ # /__________\ /____\/____\ # # and normalizing the resulting vectors to the surface of a sphere def subdivide(tri,deep): if deep: a = tri[0] b = tri[1] c = tri[2] a1 = norm(A(tri[0])) b1 = norm(A(tri[1])) c1 = norm(A(tri[2])) d = tuple(norm(a1+b1)) e = tuple(norm(b1+c1)) f = tuple(norm(c1+a1)) return subdivide((a,d,f), deep-1) + subdivide((d,e,f), deep-1) +\ subdivide((d,b,e), deep-1) + subdivide((f,e,c), deep-1) else: return [tri] ## Get the specific detail level of triangles approximation of a sphere def getSphereTriangles(level): ocdec = [] for i in icosix: ocdec += subdivide((icosa[i[0]],icosa[i[1]],icosa[i[2]]),level) return ocdec # == # Instead of the above recursive scheme that orients the icosahedron with the # midpoints of six edges perpendicular to the major axes, use a ring approach # to make subdivided icosa-spheres for Triangle Strips. The vertices are # grouped in rings from the North Pole to the South Pole. Each strip zig-zags # between two rings, and the poles are surrounded by pentagonal Triangle Fans. # # ---------------- # # The pattern of five-fold vertices in a "twisted orange-slice" segment # covering one-fifth of the icosahedron is: # # ... [3,0] ... (North Pole) # / | \ # / | ... # / | # ... [2,1]---[2,0] ... # / \ / \ # ... \ / \ ... # \ / \ / # ... [1,1]---[1,0] ... # | / # ... | / # \ | / # ... [0,0] ... (South Pole) # # ---------------- # # Higher subdivision levels step the strip verts along the icos edges, # interpolating intermediate points on the icos and projecting each onto the # sphere. Note: sphere vertex normals are the same as their coords. # # The "*"s show approximate vertex locations at each subdivision level. # Bands are numbered from South to North. (Reason explained below.) # Sub-band numbers are in angle-brackets, "<>". # # Level 0 [3*0] Level 1 [6*0] Level 2 [12*0] _<3> # / | (2 steps) / | <1> (4 steps) *-* _<2> # Band 2 / | * - * *-*-* _<1> # / | / | / | <0> *-*-*-* _<0> # [2*1]- -[2*0] => [4*2]-*-[4*0] => [8*4]***[8*0] _<3> # \ / \ \ / \ / \ <1> *-*-*-*-* _<2> # Band 1 \ / \ * - * - * *-*-*-*-* _<1> # \ / \ \ / \ / \ <0> *-*-*-*-* _<0> # [1*1]---[1*0] [2*2]-*-[2*0] [4*4]***[4*0]_<3> # | / | \ | / <1> *-*-*-* _<2> # Band 0 | / * - * *-*-* _<1> # | / | / <0> *-* _<0> # [0*0] [0*0] [0*0] # # ---------------- # # The reason for rotating east, then going west along the latitude lines, is # that the "grain" of triangle strip diagonals runs that way in the middle # band of the icos: # # Triangle Strip triangles # # 6 ----- 4 ----- 2 # \5,4,6/ \3,2,4/ \ # ... \ / \ / \ # \ /3,4,5\ /1,2,3\ # 5 ----- 3 ----- 1 <- Vertex order # # This draws triangles 1-2-3, 3-2-4, 3-4-5, and 5-4-6, all counter-clockwise # so the normal directions don't flip-flop. # # ---------------- # # This version optimizes by concatenating vertices for separate Triangle Fan # and Triangle Strip calls into a single long Triangle Strip to minimize calls. # # In the "pentagon cap" band at the top of the icos, points 2, 4, and 6 in the # above example are collapsed to the North Pole; at the bottom, points 1, 3, # and 5 are collapsed to the South Pole. This makes "null triangles" with one # zero-length edge, and the other two edges echoing one of the other triangle # edges (5,4,6 and 3,2,4 at the top, and 3,4,5 and 1,2,3 at the bottom.) # # In the subdivided caps, the icosahedron bands are split into horizontal # sub-bands. In the tapering-in sub-bands in the North cap, there is one less # vertex on the top edges of sub-bands, so we collapse the *LAST* triangle # there (e.g. 5,4,6 above) On the bottom edges of the South cap bands there # is one less vertex, so we collapse the *FIRST* triangle (e.g. 1,2,3.) # # Similarly, moving from the end of each sub-band to the beginning of the next # requires a *pair* of null triangles. We get that by simply concatenating the # wrapped triangle strips. We orient point pairs in the triangle strip from # south to north, so this works as long as we jog northward between (sub-)bands. # This is the reason we start the Triangle Strip with the South Pole band. # def getSphereTriStrips(level): steps = 2**level points = [] # Triangle Strip vertices o be returned. # Construct an icosahedron with two vertices at the North and South Poles, # +-1 on the Y axis, as you look toward the X-Y plane with the Z axis # pointing out at you. The "middle ring" vertices are all at the same # +-latitudes, on the intersection circles of the globe with a polar-axis # cylinder of the proper radius. # # The third "master vertex" of the icosahedron is placed on the X-Y plane, # which intersects the globe at the Greenwich Meridian (the semi-circle at # longitude 0, through Greenwich Observatory, 5 miles south-east of London.) # # The X (distance from the polar axis) and Y (height above the equatorial # plane) of the master vertex make a "golden rectangle", one unit high by # "phi" (1.6180339887498949) wide. We normalize this to put it on the # unit-radius sphere, and take the distance from the axis as the cylinder # radius used to generate the rest of the vertices of the two middle rings. # # Plotted on the globe, the master vertex (first vertex of the North ring) # is lat-long 31.72,0 due south of London in Africa, about 45 miles # south-southwest of Benoud, Algeria. The first vertex of the south ring is # rotated 1/10 of a circle east, at lat-long -31.72,36 in the south end of # the Indian Ocean, about 350 miles east-southeast of Durban, South Africa. # vert0 = norm(V(phi,1,0)) # Project the "master vertex" onto a unit sphere. cylRad = vert0[0] # Icos vertex distance from the Y axis. ringLat = atan2(vert0[1], vert0[0]) * degreesPerRadian # Latitude +-31.72 . # Basic triangle-strip icosahedron vertices. Start and end with the Poles. # Reflect the master vertex into the southern hemisphere and rotate 5 copies # to make the middle rings of 5 vertices at North and South latitudes. p2_5 = 2*pi / 5.0 # Simplify indexing by replicating the Poles, so everything is in fives. icosRings = [ 5 * [V(0.0, -1.0, 0.0)], # South Pole. # South ring, first edge *centered on* the Greenwich Meridian. [V(cylRad*cos((i-.5)*p2_5),-vert0[1], cylRad*sin((i-.5)*p2_5)) for i in range(5)], # North ring, first vertex *on* the Greenwich Meridian. [V(cylRad*cos(i*p2_5 ), vert0[1], cylRad*sin(i*p2_5)) for i in range(5)], 5 * [V(0.0, 1.0, 0.0)] ] # North Pole. # Three bands, going from bottom to top (South to North.) for band in range(3): lowerRing = icosRings[band] upperRing = icosRings[band+1] # Subdivide bands into sub-bands. When level == 0, steps == 1, # subBand == 0, and we get just the icosahedron out. (Really!) for subBand in range(steps): # Account for the tapering-in at the poles, making less points on # one edge of a sub-band than there are on the other edge. botOffset = 0 if band is 0: # South. botSteps = max(subBand, 1) # Don't divide by zero. topSteps = subBand + 1 # Collapse the *first* triangle of south sub-band bottom edges. botOffset = -1 elif band is 1: # Middle. botSteps = topSteps = steps else: # band is 2: North. botSteps = steps - subBand topSteps = max(steps - (subBand+1), 1) pass subBandSteps = max(botSteps, topSteps) # Do five segments, clockwise around the North Pole (East to West.) for seg in range(5): nextseg = (seg+1) % 5 # Wrap-around. # Interpolate ends of bottom & top edges of a sub-band segment. fractBot = float(subBand)/float(steps) fractTop = float(subBand+1)/float(steps) sbBotRight = fractBot * upperRing[seg] + \ (1.0-fractBot) * lowerRing[seg] sbTopRight = fractTop * upperRing[seg] + \ (1.0-fractTop) * lowerRing[seg] sbBotLeft = fractBot * upperRing[nextseg] + \ (1.0-fractBot) * lowerRing[nextseg] sbTopLeft = fractTop * upperRing[nextseg] + \ (1.0-fractTop) * lowerRing[nextseg] # Output the right end of the first segment of the sub-band. # We'll end up wrapping around to this same pair of points at # the left end of the last segment of the sub-band. if seg == 0: # Project verts from icosahedron faces onto the unit sphere. points += [norm(sbBotRight), norm(sbTopRight)] # Step across the sub-band edges from right to left, # stitching triangle pairs from their lower to upper edges. for step in range(1, subBandSteps+1): # Interpolate step point pairs along the sub-band edges. fractLower = float(step+botOffset)/float(botSteps) lower = fractLower * sbBotLeft + \ (1.0-fractLower) * sbBotRight # Collapse the *last* triangle of north sub-band top edges. fractUpper = float(min(step, topSteps))/float(topSteps) upper = fractUpper * sbTopLeft + \ (1.0-fractUpper) * sbTopRight # Output verts, projected from icos faces onto unit sphere. points += [norm(lower), norm(upper)] continue # step continue # seg continue # subBand continue # band return points def indexVerts(verts, close): """ Compress a vertex array into an array of unique vertices, and an array of index values into the unique vertices. This is good for converting input for glDrawArrays into input for glDrawElements. The second arg is 'close', the distance between vertices which are close enough to be considered a single vertex. The return value is a pair of arrays (index, verts). """ unique = [] index = [] for v in verts: for i in range(len(unique)): if vlen(unique[i] - v) < close: index += [i] break pass else: index += [len(unique)] unique += [v] pass continue return (index, unique) # == def init_cyls(): # generate two circles in space as 13-gons, one rotated half a segment with # respect to the other these are used as cylinder ends [not quite true # anymore, see comments just below] slices = 13 circ1 = map((lambda n: n*2.0*pi/slices), range(slices+1)) circ2 = map((lambda a: a+pi/slices), circ1) drawing_globals.drum0 = drum0 = map((lambda a: (cos(a), sin(a), 0.0)), circ1) drum1 = map((lambda a: (cos(a), sin(a), 1.0)), circ2) drum1n = map((lambda a: (cos(a), sin(a), 0.0)), circ2) #grantham 20051213 I finally decided the look of the oddly twisted cylinder # bonds was not pretty enough, so I made a "drum2" which is just drum0 with # a 1.0 Z coordinate, a la drum1. #bruce 060609: this apparently introduced the bug of the drum1 end-cap of a # cylinder being "ragged" (letting empty space show through), which I fixed # by using drum2 for that cap rather than drum1. drum1 is no longer used # except as an intermediate value in the next few lines. drawing_globals.drum2 = drum2 = map((lambda a: (cos(a), sin(a), 1.0)), circ1) # This edge list zips up the "top" vertex and normal and then the "bottom" # vertex and normal. Thus each tuple in the sequence would be (vtop, ntop, # vbot, nbot) [grantham 20051213] # (bruce 051215 simplified the python usage in a way which should create the # same list.) drawing_globals.cylinderEdges = zip(drum0, drum0, drum2, drum0) circle = zip(drum0[:-1],drum0[1:],drum1[:-1]) +\ zip(drum1[:-1],drum0[1:],drum1[1:]) circlen = zip(drum0[:-1],drum0[1:],drum1n[:-1]) +\ zip(drum1n[:-1],drum0[1:],drum1n[1:]) drawing_globals.cap0n = (0.0, 0.0, -1.0) drawing_globals.cap1n = (0.0, 0.0, 1.0) drum0.reverse() return init_cyls() def init_motors(): ###data structure to construct the rotation sign for rotary motor numSeg = 20 rotS = map((lambda n: pi/2+n*2.0*pi/numSeg), range(numSeg*3/4 + 1)) zOffset = 0.005 scaleS = 0.4 drawing_globals.rotS0n = rotS0n = map( (lambda a: (scaleS*cos(a), scaleS*sin(a), 0.0 - zOffset)), rotS) drawing_globals.rotS1n = rotS1n = map( (lambda a: (scaleS*cos(a), scaleS*sin(a), 1.0 + zOffset)), rotS) ###Linear motor arrow sign data structure drawing_globals.halfHeight = 0.45 drawing_globals.halfEdge = halfEdge = 3.0 * scaleS * sin(pi/numSeg) arrow0Vertices = [ (rotS0n[-1][0]-halfEdge, rotS0n[-1][1], rotS0n[-1][2]), (rotS0n[-1][0]+halfEdge, rotS0n[-1][1], rotS0n[-1][2]), (rotS0n[-1][0], rotS0n[-1][1] + 2.0*halfEdge, rotS0n[-1][2])] arrow0Vertices.reverse() drawing_globals.arrow0Vertices = arrow0Vertices drawing_globals.arrow1Vertices = [ (rotS1n[-1][0]-halfEdge, rotS1n[-1][1], rotS1n[-1][2]), (rotS1n[-1][0]+halfEdge, rotS1n[-1][1], rotS1n[-1][2]), (rotS1n[-1][0], rotS1n[-1][1] + 2.0*halfEdge, rotS1n[-1][2])] drawing_globals.halfEdge = halfEdge = 1.0/3.0 ##1.0/8.0 drawing_globals.linearArrowVertices = [ (0.0, -halfEdge, 0.0), (0.0, halfEdge, 0.0), (0.0, 0.0,2*halfEdge)] return init_motors() def init_diamond(): # a chunk of diamond grid, to be tiled out in 3d drawing_globals.sp0 = sp0 = 0.0 #bruce 051102 replaced 1.52 with this constant (1.544), # re bug 900 (partial fix.) drawing_globals.sp1 = sp1 = DIAMOND_BOND_LENGTH / sqrt(3.0) sp2 = 2.0*sp1 sp3 = 3.0*sp1 drawing_globals.sp4 = sp4 = 4.0*sp1 digrid=[[[sp0, sp0, sp0], [sp1, sp1, sp1]], [[sp1, sp1, sp1], [sp2, sp2, sp0]], [[sp2, sp2, sp0], [sp3, sp3, sp1]], [[sp3, sp3, sp1], [sp4, sp4, sp0]], [[sp2, sp0, sp2], [sp3, sp1, sp3]], [[sp3, sp1, sp3], [sp4, sp2, sp2]], [[sp2, sp0, sp2], [sp1, sp1, sp1]], [[sp1, sp1, sp1], [sp0, sp2, sp2]], [[sp0, sp2, sp2], [sp1, sp3, sp3]], [[sp1, sp3, sp3], [sp2, sp4, sp2]], [[sp2, sp4, sp2], [sp3, sp3, sp1]], [[sp3, sp3, sp1], [sp4, sp2, sp2]], [[sp4, sp0, sp4], [sp3, sp1, sp3]], [[sp3, sp1, sp3], [sp2, sp2, sp4]], [[sp2, sp2, sp4], [sp1, sp3, sp3]], [[sp1, sp3, sp3], [sp0, sp4, sp4]]] drawing_globals.digrid = A(digrid) drawing_globals.DiGridSp = sp4 return init_diamond() def init_cube(): drawing_globals.cubeVertices = cubeVertices = [ [-1.0, 1.0, -1.0], [-1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, -1.0], [-1.0, -1.0, -1.0], [-1.0, -1.0, 1.0], [1.0, -1.0, 1.0], [1.0, -1.0, -1.0]] #bruce 051117: compute this rather than letting a subroutine hardcode it as # a redundant constant flatCubeVertices = [] for threemore in cubeVertices: flatCubeVertices.extend(threemore) flatCubeVertices = list(flatCubeVertices) #k probably not needed drawing_globals.flatCubeVertices = flatCubeVertices if 1: # remove this when it works flatCubeVertices_hardcoded = [-1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0] assert flatCubeVertices == flatCubeVertices_hardcoded sq3 = sqrt(3.0)/3.0 drawing_globals.cubeNormals = [ [-sq3, sq3, -sq3], [-sq3, sq3, sq3], [sq3, sq3, sq3], [sq3, sq3, -sq3], [-sq3, -sq3, -sq3], [-sq3, -sq3, sq3], [sq3, -sq3, sq3], [sq3, -sq3, -sq3]] drawing_globals.cubeIndices = [ [0, 1, 2, 3], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [0, 3, 7, 4], [4, 7, 6, 5]] return init_cube() # Some variables used by the Lonsdaleite lattice construction. ux = 1.262 uy = 0.729 dz = 0.5153 ul = 1.544 drawing_globals.XLen = XLen = 2*ux drawing_globals.YLen = YLen = 6*uy drawing_globals.ZLen = ZLen = 2*(ul + dz) def _makeLonsCell(): """ Data structure to construct a Lonsdaleite lattice cell """ lVp = [# 2 outward vertices [-ux, -2*uy, 0.0], [0.0, uy, 0.0], # Layer 1: 7 vertices [ux, -2*uy, ul], [-ux, -2*uy, ul], [0.0, uy, ul], [ux, 2*uy, ul+dz], [-ux, 2*uy, ul+dz], [0.0, -uy, ul+dz], [-ux, 4*uy, ul], # Layer 2: 7 vertices [ux, -2*uy, 2*(ul+dz)], [-ux, -2*uy, 2*(ul+dz)], [0.0, uy, 2*(ul+dz)], [ux, 2*uy, 2*ul+dz], [-ux, 2*uy, 2*ul+dz], [0.0, -uy, 2*ul+dz], [-ux, 4*uy, 2*(ul+dz)] ] res = [ # 2 outward vertical edges for layer 1 [lVp[0], lVp[3]], [lVp[1], lVp[4]], # 6 xy Edges for layer 1 [lVp[2], lVp[7]], [lVp[3], lVp[7]], [lVp[7], lVp[4]], [lVp[4], lVp[6]], [lVp[4], lVp[5]], [lVp[6], lVp[8]], # 2 outward vertical edges for layer 2 [lVp[14], lVp[7]], [lVp[13], lVp[6]], # 6 xy Edges for layer 2 [lVp[14], lVp[9]], [lVp[14], lVp[10]], [lVp[14], lVp[11]], [lVp[11], lVp[13]], [lVp[11], lVp[12]], [lVp[13], lVp[15]] ] return res drawing_globals.lonsEdges = _makeLonsCell()
NanoCAD-master
cad/src/graphics/drawing/shape_vertices.py
NanoCAD-master
cad/src/graphics/drawing/__init__.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ ShaderGlobals.py - "global state" about a kind of shader in a GL resource context @author: Russ, Bruce @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: Russ developed some of this code in other files, mainly setup_draw.py, glprefs.py, and drawing_globals.py. Bruce 090303 refactored it out of those files to create this class and its subclasses. Motivations: permit all prefs changes during a session, and general modularity and cleanup. """ from OpenGL.GL import glBegin from OpenGL.GL import GL_COMPILE from OpenGL.GL import glEnd from OpenGL.GL import glEndList from OpenGL.GL import GL_EXTENSIONS from OpenGL.GL import glGenLists from OpenGL.GL import glGetString from OpenGL.GL import glNewList from OpenGL.GL import GL_QUADS from OpenGL.GL import glVertex3fv from geometry.VQT import A from utilities.debug import print_compact_traceback # == class ShaderGlobals: """ Subclasses collect the methods associated with one kind of shader. Instances are for a specific OpenGL "resource context". Covered here: - access to debug_prefs for whether to try to use this kind of shader - flags about what warnings/errors have been printed in this session - higher-level methods for whether to use shaders in specific ways - status of trying to initialize this shader in this resource context - the shader itself (note: if it exists, it knows whether it had an error) - the associated GLPrimitiveBuffer """ # class constants (don't depend on subclass (kind of shader) or resource context) shaderCubeVerts = [ # not used (-1.0, -1.0, -1.0), ( 1.0, -1.0, -1.0), (-1.0, 1.0, -1.0), ( 1.0, 1.0, -1.0), (-1.0, -1.0, 1.0), ( 1.0, -1.0, 1.0), (-1.0, 1.0, 1.0), ( 1.0, 1.0, 1.0), ] shaderCubeIndices = [ # not used [0, 1, 3, 2], # -Z face. [4, 5, 7, 6], # +Z face. [0, 1, 5, 4], # -Y face. [2, 3, 7, 6], # +Y face. [0, 2, 6, 4], # -X face. [1, 3, 7, 5], # +X face. ] # instance variable default values shader = None # a public attribute, None or a GLShaderObject primitiveBuffer = None _tried_shader_init = False # don't try it twice in the same session ##### fix: shouldn't use shader source code, do that later at runtime; # but for now, constructing a shader also loads its source code, # and we have no provision to change that later even if it depends on prefs. # This also relates to the Q of whether shader.error can be set on construction -- it means it can. # Several other comments here are about this. Fixing it is high priority # after this refactoring. [bruce 090304] # access methods def shader_available(self): """ @return: whether our shader is available for use (ignoring preferences). @note: this just returns (self.shader and not self.shader.error); all of those are public attributes, but using this method is preferred over testing them directly, so it's less likely you'll forget to test shader.error. """ return self.shader and not self.shader.error # init or setup methods def setup_if_needed_and_not_failed(self): """ This must be called when the correct GL context is current, and only if this kind of shader is now desired for drawing. But it can be called many times per session (e.g. at start of each drawing frame which wants to use this shader). If this kind of shader needs setup (i.e. was not setup successfully in this session) and didn't fail to be setup, set it up now. Print message on any error. Caller can determine whether this worked (now or later) by a boolean test on self.shader_available(). @see: self.shader_available(). """ if not self.shader and not self._tried_shader_init: self._tried_shader_init = True # set early in case of exceptions # note: in future, if we support reloading shader source code, # we'll need to reset this flag (and self.shader) to try new # source code. try: self._try_shader_init() except: print_compact_traceback( "Error initializing %s shaders (or primitiveBuffers): " % self.primtype ) self.shader = None # precaution pass if not self.shader_available(): # Note: it's possible that self.shader but also # self.shader.error, e.g. due to a GLSL syntax error or # version error. When source code can be reloaded later, # due to changes in preferences which affect it, # we may want to set an additional error flag for creation # errors (to prevent us from even trying to load new code), # to distinguish them from code-loading errors (after which # it's ok to try again to load new code). print "Shader setup failed:", self # precaution in case more specific message was not printed print " To work around this error, we'll use non-shader drawing for %ss." % self.primtype print " You can avoid trying to load GLSL shaders each time NE1 starts up" print " by unsetting appropriate GLPane debug_prefs. Or, updating your" print " graphics card drivers might make shaders work, speeding up graphics." print pass return def _try_shader_init(self): """ This runs at most once, when this kind of shader is first needed. It should try to set up this kind of shader in this GL resource context, and if this works, set self.shader to the shader. When anything goes wrong it should simply print an error and return without setting self.shader (or setting both that and self.shader.error). It's ok for this to raise an exception, though when practical it's preferable to print an error and exit normally (so the error message can be more specific and understandable). (If we ever have more than one GL resource context, we'll want to factor it into the part that doesn't depend on context (to avoid redundant error messages) and the part that does.) """ if glGetString(GL_EXTENSIONS).find("GL_ARB_shader_objects") >= 0: print "note: this session WILL try to use %s-shaders" % self.primtype pass else: # REVIEW: # Could we support shaders with the older GL_ARB_vertex_program and # GL_ARB_fragment_program with some work? Get assembly-like vertex # and fragment programs from the GLSL source using an option of the # nVidia Cg compiler. Needs some loading API changes too... # [Russ comment, late 2008] print "note: this session WOULD try to use %s-shaders,\n" % self.primtype, \ "but GL_EXTENSION GL_ARB_shader_objects is not supported.\n" return shader_class = self.get_shader_class() self.shader = shader_class() if not self.shader.error: # see also shader_available # Note: self.shader.error is possible at this stage; see above. print "%s shader initialization is complete." % self.primtype primitiveBuffer_class = self.get_primitiveBuffer_class() self.primitiveBuffer = primitiveBuffer_class( self) print "%s primitive buffer initialization is complete." % self.primtype print return # == def _setup_shaderCubeList(self): # not used self.shaderCubeList = glGenLists(1) glNewList(self.shaderCubeList, GL_COMPILE) verts = self.shaderCubeVerts indices = self.shaderCubeIndices glBegin(GL_QUADS) for i in range(6): for j in range(4): glVertex3fv(A(verts[indices[i][j]])) continue continue glEnd() glEndList() pass # end of class ShaderGlobals # == class SphereShaderGlobals(ShaderGlobals): """ """ # class constants (don't depend on resource context) primtype = "sphere" # Special billboard drawing pattern for the sphere shader. # Use with shaders where drawing patterns are applied in eye (camera) # coordinates. The billboard stays between the eye and the primitive. billboardVerts = [ (-1.0, -1.0, 1.0), ( 1.0, -1.0, 1.0), (-1.0, 1.0, 1.0), ( 1.0, 1.0, 1.0), ] billboardIndices = [ [0, 1, 3, 2] # +Z face. ] def get_shader_class(self): # done at runtime, so import error won't prevent startup #### refile this comment from graphics.drawing.gl_shaders import GLSphereShaderObject return GLSphereShaderObject def get_primitiveBuffer_class(self): from graphics.drawing.GLSphereBuffer import GLSphereBuffer return GLSphereBuffer pass # == class CylinderShaderGlobals(ShaderGlobals): """ """ # class constants (don't depend on resource context) primtype = "cylinder" # Special billboard drawing pattern for the cylinder shader. billboardVerts = [ (0.0, -1.0, 1.0), (1.0, -1.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0), ] billboardIndices = [ [0, 1, 2, 3] # +Z face. ] def get_shader_class(self): from graphics.drawing.gl_shaders import GLCylinderShaderObject return GLCylinderShaderObject def get_primitiveBuffer_class(self): from graphics.drawing.GLCylinderBuffer import GLCylinderBuffer return GLCylinderBuffer pass # end
NanoCAD-master
cad/src/graphics/drawing/ShaderGlobals.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ Creates a schematic "trace" drawing for PeptideBuilder. @author: Piotr @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. @license: GPL """ from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushMatrix from OpenGL.GL import glTranslatef from geometry.VQT import norm, vlen, V, cross from utilities.prefs_constants import DarkBackgroundContrastColor_prefs_key from utilities.constants import blue, gray import foundation.env as env from graphics.drawing.CS_draw_primitives import drawline, drawsphere from graphics.drawing.drawers import drawPoint from graphics.drawing.drawers import drawCircle from protein.commands.InsertPeptide.PeptideGenerator import get_unit_length def drawPeptideTrace(alphaCarbonProteinChunk): """ Draws a protein backbone trace using atoms stored in I{alphaCarbonProteinChunk}. @param alphaCarbonProteinChunk: a special (temporary) chunk that contains only the alpha carbon atoms in the peptide backbone @param alphaCarbonProteinChunk: Chunk @see PeptideLine_GraphicsMode.Draw_other(), PeptideGenerator.make_aligned() """ if alphaCarbonProteinChunk and alphaCarbonProteinChunk.atoms: last_pos = None atomitems = alphaCarbonProteinChunk.atoms.items() atomitems.sort() alphaCarbonAtomsList = [atom for (key, atom) in atomitems] for atom in alphaCarbonAtomsList: drawsphere(blue, atom.posn(), 0.2, 1) if last_pos: drawline(gray, last_pos, atom.posn(), width=2) last_pos = atom.posn() pass pass return # drawPeptideTrace_orig is the original function for drawing a peptide # trace. This function is deprecated and marked for removal. I'm keeping it # here for reference for the time being. # --Mark 2008-12-23 def drawPeptideTrace_orig(endCenter1, endCenter2, phi, psi, glpaneScale, lineOfSightVector, beamThickness = 2.0, beam1Color = None, beam2Color = None, stepColor = None ): """ Draws the Peptide in a schematic display. @param endCenter1: Nanotube center at end 1 @type endCenter1: B{V} @param endCenter2: Nanotube center at end 2 @type endCenter2: B{V} @param phi: Peptide phi angle @type phi: float @param psi: Peptide psi angle @type psi: float @param glpaneScale: GLPane scale used in scaling arrow head drawing @type glpaneScale: float @param lineOfSightVector: Glpane lineOfSight vector, used to compute the the vector along the ladder step. @type: B{V} @param beamThickness: Thickness of the two ladder beams @type beamThickness: float @param beam1Color: Color of beam1 @param beam2Color: Color of beam2 @see: B{DnaLineMode.Draw } (where it is used) for comments on color convention @deprecated: Use drawPeptideTrace() instead. """ ladderWidth = 3.0 ladderLength = vlen(endCenter1 - endCenter2) cntRise = get_unit_length(phi, psi) # Don't draw the vertical line (step) passing through the startpoint unless # the ladderLength is atleast equal to the cntRise. # i.e. do the drawing only when there are atleast two ladder steps. # This prevents a 'revolving line' effect due to the single ladder step at # the first endpoint if ladderLength < cntRise: return unitVector = norm(endCenter2 - endCenter1) if beam1Color is None: beam1Color = env.prefs[DarkBackgroundContrastColor_prefs_key] if beam2Color is None: beam2Color = env.prefs[DarkBackgroundContrastColor_prefs_key] if stepColor is None: stepColor = env.prefs[DarkBackgroundContrastColor_prefs_key] glDisable(GL_LIGHTING) glPushMatrix() glTranslatef(endCenter1[0], endCenter1[1], endCenter1[2]) pointOnAxis = V(0, 0, 0) vectorAlongLadderStep = cross(-lineOfSightVector, unitVector) unitVectorAlongLadderStep = norm(vectorAlongLadderStep) ladderBeam1Point = pointOnAxis + \ unitVectorAlongLadderStep * 0.5 * ladderWidth ladderBeam2Point = pointOnAxis - \ unitVectorAlongLadderStep * 0.5 * ladderWidth # Following limits the arrowHead Size to the given value. When you zoom out, # the rest of ladder drawing becomes smaller (expected) and the following # check ensures that the arrowheads are drawn proportinately. (Not using a # 'constant' to do this as using glpaneScale gives better results) if glpaneScale > 40: arrowDrawingScale = 40 else: arrowDrawingScale = glpaneScale x = 0.0 while x < ladderLength: drawPoint(stepColor, pointOnAxis) drawCircle(stepColor, pointOnAxis, ladderWidth * 0.5, unitVector) previousPoint = pointOnAxis previousLadderBeam1Point = ladderBeam1Point previousLadderBeam2Point = ladderBeam2Point pointOnAxis = pointOnAxis + unitVector * cntRise x += cntRise ladderBeam1Point = previousPoint + \ unitVectorAlongLadderStep * 0.5 * ladderWidth ladderBeam2Point = previousPoint - \ unitVectorAlongLadderStep * 0.5 * ladderWidth if previousLadderBeam1Point: drawline(beam1Color, previousLadderBeam1Point, ladderBeam1Point, width = beamThickness, isSmooth = True ) drawline(beam2Color, previousLadderBeam2Point, ladderBeam2Point, width = beamThickness, isSmooth = True ) #drawline(stepColor, ladderBeam1Point, ladderBeam2Point) glPopMatrix() glEnable(GL_LIGHTING) return
NanoCAD-master
cad/src/graphics/drawing/drawPeptideTrace.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ CS_workers.py - Drawing functions for primitives drawn by the ColorSorter. @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originated by Josh in drawer.py . Various developers extended it since then. Brad G. added ColorSorter features. 080311 piotr Added a "drawpolycone_multicolor" function for drawing polycone tubes with per-vertex colors (necessary for DNA display style) 080420 piotr Solved highlighting and selection problems for multi-colored objects (e.g. rainbow colored DNA structures). 080519 russ pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py """ _DRAW_BONDS = True # Debug/test switch. Similar constant in chunk.py. # the imports from math vs. Numeric are as discovered in existing code # as of 2007/06/25. It's not clear why acos is coming from math... from math import acos import Numeric from Numeric import pi # russ 080519 No doubt many of the following imports are unused. # When the dust settles, the unnecessary ones will be removed. from OpenGL.GL import glBegin from OpenGL.GL import glCallList from OpenGL.GL import glColor3fv from OpenGL.GL import GL_COLOR_MATERIAL from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import GL_CURRENT_BIT from OpenGL.GL import glDisable from OpenGL.GL import glDisableClientState from OpenGL.GL import glDrawArrays from OpenGL.GL import glDrawElements from OpenGL.GL import glEnable from OpenGL.GL import glEnableClientState from OpenGL.GL import glEnd from OpenGL.GL import GL_FALSE from OpenGL.GL import GL_FILL from OpenGL.GL import GL_FLOAT from OpenGL.GL import GL_FRONT from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_LIGHT_MODEL_TWO_SIDE from OpenGL.GL import glLightModelfv from OpenGL.GL import GL_LINE from OpenGL.GL import GL_LINES from OpenGL.GL import GL_LINE_SMOOTH from OpenGL.GL import glLineStipple from OpenGL.GL import GL_LINE_STIPPLE from OpenGL.GL import glLineWidth from OpenGL.GL import glNormal3fv from OpenGL.GL import glNormalPointer from OpenGL.GL import GL_NORMAL_ARRAY from OpenGL.GL import glPolygonMode from OpenGL.GL import glPopAttrib from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushAttrib from OpenGL.GL import glPushMatrix from OpenGL.GL import glRotate from OpenGL.GL import glTranslatef from OpenGL.GL import GL_TRIANGLE_STRIP from OpenGL.GL import glVertex from OpenGL.GL import glVertex3fv from OpenGL.GL import GL_VERTEX_ARRAY from OpenGL.GL import glVertexPointer from OpenGL.GL import GL_TRUE from geometry.VQT import norm, V import graphics.drawing.drawing_globals as drawing_globals # used only for GL resources related to geometric primitives, as of 090304 from graphics.drawing.drawers import renderSurface from graphics.drawing.gl_GLE import glePolyCone from graphics.drawing.gl_Scale import glScale ### Substitute this for drawsphere_worker to test drawing a lot of spheres. def drawsphere_worker_loop(params): (pos, radius, detailLevel, n) = params pos += V(-n/2, -n/2, 0) # Centered on the origin. for x in range(n): for y in range(n): newpos = pos + (x+x/10+x/100) * V(1, 0, 0) + \ (y+y/10+y/100) * V(0, 1, 0) drawsphere_worker((newpos, radius, detailLevel, 1)) continue continue return def drawsphere_worker(params): """ Draw a sphere. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below) """ (pos, radius, detailLevel, n) = params del n # KLUGE: the detailLevel can be a tuple, (vboLevel, detailLevel). # The only for reason for this is that drawsphere_worker is used # in ProteinChunks (I added a comment there saying why that's bad) # and I don't have time to clean that up now. Ideally, vboLevel # would just be another parameter, or we'd combine it with detailLevel # in some other way not constrained by backward compatibility of # this internal worker function's API. [bruce 090304] if type(detailLevel) == type(()): (vboLevel, detailLevel) = detailLevel ## vboLevel = drawing_globals.use_drawing_variant glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) glScale(radius,radius,radius) if vboLevel == 0: # OpenGL 1.0 - glBegin/glEnd tri-strips vertex-by-vertex. glCallList(drawing_globals.sphereList[detailLevel]) else: # OpenGL 1.1/1.5 - Array/VBO/IBO variants. glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) size = len(drawing_globals.sphereArrays[detailLevel]) GLIndexType = drawing_globals.sphereGLIndexTypes[detailLevel] if vboLevel == 1: # DrawArrays from CPU RAM. verts = drawing_globals.sphereCArrays[detailLevel] glVertexPointer(3, GL_FLOAT, 0, verts) glNormalPointer(GL_FLOAT, 0, verts) glDrawArrays(GL_TRIANGLE_STRIP, 0, size) elif vboLevel == 2: # DrawElements from CPU RAM. verts = drawing_globals.sphereCElements[detailLevel][1] glVertexPointer(3, GL_FLOAT, 0, verts) glNormalPointer(GL_FLOAT, 0, verts) # Can't use the C index in sphereCElements yet, fatal PyOpenGL bug. index = drawing_globals.sphereElements[detailLevel][0] glDrawElements(GL_TRIANGLE_STRIP, size, GLIndexType, index) elif vboLevel == 3: # DrawArrays from graphics RAM VBO. vbo = drawing_globals.sphereArrayVBOs[detailLevel] vbo.bind() glVertexPointer(3, GL_FLOAT, 0, None) glNormalPointer(GL_FLOAT, 0, None) glDrawArrays(GL_TRIANGLE_STRIP, 0, vbo.size) vbo.unbind() elif vboLevel == 4: # DrawElements from index in CPU RAM, verts in VBO. vbo = drawing_globals.sphereElementVBOs[detailLevel][1] vbo.bind() # Vertex and normal data comes from the vbo. glVertexPointer(3, GL_FLOAT, 0, None) glNormalPointer(GL_FLOAT, 0, None) # Can't use the C index in sphereCElements yet, fatal PyOpenGL bug. index = drawing_globals.sphereElements[detailLevel][0] glDrawElements(GL_TRIANGLE_STRIP, size, GLIndexType, index) vbo.unbind() elif vboLevel == 5: # VBO/IBO buffered DrawElements from graphics RAM. (ibo, vbo) = drawing_globals.sphereElementVBOs[detailLevel] vbo.bind() # Vertex and normal data comes from the vbo. glVertexPointer(3, GL_FLOAT, 0, None) glNormalPointer(GL_FLOAT, 0, None) ibo.bind() # Index data comes from the ibo. glDrawElements(GL_TRIANGLE_STRIP, size, GLIndexType, None) vbo.unbind() ibo.unbind() pass glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) pass glPopMatrix() return def drawwiresphere_worker(params): """ Draw a wireframe sphere. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below) """ (color, pos, radius, detailLevel) = params ## assert detailLevel == 1 # true, but leave out for speed from utilities.debug_prefs import debug_pref, Choice_boolean_True #bruce 060415 experiment, re iMac G4 wiresphere bug; fixes it! newway = debug_pref("new wirespheres?", Choice_boolean_True) oldway = not newway # These objects want a constant line color even if they are selected or # highlighted. glColor3fv(color) glDisable(GL_LIGHTING) if oldway: glPolygonMode(GL_FRONT, GL_LINE) glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) glScale(radius,radius,radius) if oldway: glCallList(drawing_globals.sphereList[detailLevel]) else: glCallList(drawing_globals.wiresphere1list) glEnable(GL_LIGHTING) glPopMatrix() if oldway: glPolygonMode(GL_FRONT, GL_FILL) return def drawcylinder_worker(params): """ Draw a cylinder. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below) @warning: our circular cross-section is approximated by a 13-gon whose alignment around the axis is chosen arbitrary, in a way which depends on the direction of the axis; negating the axis usually causes a different alignment of that 13-gon. This effect can cause visual bugs when drawing one cylinder over an identical or slightly smaller one (e.g. when highlighting a bond), unless the axes are kept parallel as opposed to antiparallel. """ if not _DRAW_BONDS: return (pos1, pos2, radius, capped) = params glPushMatrix() vec = pos2-pos1 axis = norm(vec) glTranslatef(pos1[0], pos1[1], pos1[2]) ##Huaicai 1/17/05: To avoid rotate around (0, 0, 0), which causes ## display problem on some platforms angle = -acos(axis[2])*180.0/pi if (axis[2]*axis[2] >= 1.0): glRotate(angle, 0.0, 1.0, 0.0) else: glRotate(angle, axis[1], -axis[0], 0.0) glScale(radius,radius,Numeric.dot(vec,vec)**.5) glCallList(drawing_globals.CylList) if capped: glCallList(drawing_globals.CapList) glPopMatrix() return def drawpolycone_worker(params): """ Draw a polycone. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below) """ if not _DRAW_BONDS: return (pos_array, rad_array) = params glePolyCone(pos_array, None, rad_array) return def drawpolycone_multicolor_worker(params): """ Draw a polycone. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below) piotr 080311: this variant accepts a color array as an additional parameter """ # Note: See the code in class ColorSorter for GL_COLOR_MATERIAL objects. (pos_array, color_array, rad_array) = params glEnable(GL_COLOR_MATERIAL) # have to enable GL_COLOR_MATERIAL for # the GLE function glPushAttrib(GL_CURRENT_BIT) # store current attributes in case glePolyCone # modifies the (e.g. current color) # piotr 080411 glePolyCone(pos_array, color_array, rad_array) glPopAttrib() # This fixes the 'disappearing cylinder' bug # glPopAttrib doesn't take any arguments # piotr 080415 glDisable(GL_COLOR_MATERIAL) return def drawsurface_worker(params): """Draw a surface. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below)""" (pos, radius, tm, nm) = params glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) glScale(radius,radius,radius) renderSurface(tm, nm) glPopMatrix() return def drawline_worker(params): """ Draw a line. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below) """ (endpt1, endpt2, dashEnabled, stipleFactor, width, isSmooth) = params ###glDisable(GL_LIGHTING) ###glColor3fv(color) if dashEnabled: glLineStipple(stipleFactor, 0xAAAA) glEnable(GL_LINE_STIPPLE) if width != 1: glLineWidth(width) if isSmooth: glEnable(GL_LINE_SMOOTH) glBegin(GL_LINES) glVertex(endpt1[0], endpt1[1], endpt1[2]) glVertex(endpt2[0], endpt2[1], endpt2[2]) glEnd() if isSmooth: glDisable(GL_LINE_SMOOTH) if width != 1: glLineWidth(1.0) # restore default state if dashEnabled: glDisable(GL_LINE_STIPPLE) ###glEnable(GL_LIGHTING) return def drawtriangle_strip_worker(params): """ Draw a triangle strip using a list of triangle vertices and (optional) normals. """ # Note: See the code in class ColorSorter for GL_COLOR_MATERIAL objects. # piotr 080904 - This method could be optimized by using vertex # arrays or VBOs. (triangles, normals, colors) = params # It needs to support two-sided triangles, therefore we disable # culling and enable two-sided lighting. These settings have to be # turned back to default setting. glDisable(GL_CULL_FACE) glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE) # Use color material mode if colors are present. if colors: glEnable(GL_COLOR_MATERIAL) glBegin(GL_TRIANGLE_STRIP) if normals: if colors: for p in range(len(triangles)): n = normals[p] v = triangles[p] c = colors[p] glNormal3fv(n) glColor3fv(c[:3]) glVertex3fv(v) else: for p in range(len(triangles)): n = normals[p] v = triangles[p] glNormal3fv(n) glVertex3fv(v) else: for v in triangles: glVertex3fv(v) glEnd() if colors: glDisable(GL_COLOR_MATERIAL) # piotr 080904 - are these settings really default? glEnable(GL_CULL_FACE) glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE) return
NanoCAD-master
cad/src/graphics/drawing/CS_workers.py
# Copyright 2005-2008 Nanorex, Inc. See LICENSE file for details. """ glselect_name_dict.py - allocate GL_SELECT names and record their owners. @author: Bruce @version: $Id$ @copyright: 2005-2008 Nanorex, Inc. See LICENSE file for details. Module classification: [bruce 080223] It imports nothing, but the code that needs to use it is OpenGL drawing code or a framework that supports it, so it seems more natural as graphics/drawing. (It's really an "opengl drawing utility".) History: bruce 080220 split this out of env.py so we can make it per-assy. """ _last_glselect_name = 0 def _new_glselect_name(): """ Return a session-unique 32-bit unsigned int (not 0) for use as a GL_SELECT name. @note: these are unique even between instances of class glselect_name_dict. """ #e We could recycle these for dead objects (and revise docstring), # but that's a pain, and unneeded (I think), since it's very unlikely # we'll create more than 4 billion objects in one session. global _last_glselect_name _last_glselect_name += 1 return _last_glselect_name class glselect_name_dict(object): """ Allocate OpenGL GL_SELECT names for use when drawing one model (e.g. an assembly), and record their owners. @note: The allocated names are session-unique 32-bit unsigned ints (not 0). They are unique even between instances of this class. @note: Callers are free to share one instance of this class over multiple models, or (with suitable changes in current code in GLPane) to use more than one instance for objects drawn together in the same frame. @note: The allocated names can be used in OpenGL display lists, provided their owning objects remain alive as long as those display lists remain in use. """ def __init__(self): self.obj_with_glselect_name = {} # public for lookup # [Note: we might make this private # when access from env.py is no longer needed] # TODO: clear this when destroying the assy which owns self def alloc_my_glselect_name(self, obj): """ Allocate and return a new GL_SELECT name, recording obj as its owner. Obj should provide the Selobj_API so it can handle GLPane callbacks during hit-testing. @see: Selobj_API """ glname = _new_glselect_name() self.obj_with_glselect_name[glname] = obj return glname def object_for_glselect_name(self, glname): """ #doc [todo: get material from docstring of same method in assembly.py] """ return self.obj_with_glselect_name.get( glname) # Todo: add a variant of object_for_glselect_name to which the entire # name stack should be passed. Current code (as of 080220) passes the last # (innermost) element of the name stack. # Maybe todo: add methods for temporarily removing glname from dict (without # deallocating it) and for restoring it, so killed objects needn't have # names in the dict. This would mean we needn't remove the name when # destroying a killed object, thus, needn't find the object at all. But when # this class is per-assy, there won't be a need for that when destroying an # entire assy, so it might not be needed at all. def dealloc_my_glselect_name(self, obj, glname): """ #doc [todo: get material from docstring of same method in assembly.py] @note: the glname arg is permitted to be 0 or None, in which case we do nothing, to make it easier for callers to implement repeatable destroy methods which forget their glname, or work if they never allocated one yet. (Note that this is only ok because we never allocate a glname of 0.) @see: Selobj_API """ # objs have to pass the glname, since we don't know where they keep it # and don't want to have to keep a reverse dict; but we make sure they # own it before zapping it! #e This function could be dispensed with if our dict was weak, but maybe # it's useful for other reasons too, who knows. if not glname: return obj1 = self.obj_with_glselect_name.get(glname) if obj1 is obj: del self.obj_with_glselect_name[glname] ## elif obj1 is None: ## # Repeated destroy should be legal, and might call this (unlikely, ## # since obj would not know glname -- hmm... ok, zap it.) ## pass else: print ("bug: %s %r: real owner is %r, not" % ("dealloc_my_glselect_name(obj, glname) mismatch for glname", glname, obj1)), obj # Print obj separately in case of exceptions in its repr. return pass # end of class # end
NanoCAD-master
cad/src/graphics/drawing/glselect_name_dict.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GLPrimitiveBuffer.py -- Manage VBO space for drawing primitives in large batches. @author: Russ @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originally written by Russ Fish; designed together with Bruce Smith. ================================================================ See design comments on: * GL contexts, CSDLs and DrawingSet in DrawingSet.py * TransformControl in TransformControl.py * VBOs, IBOs, and GLPrimitiveBuffer in GLPrimitiveBuffer.py * GLPrimitiveSet in GLPrimitiveSet in GLPrimitiveSet.py == VBOs == * VBOs (Vertex Buffer Objects) in graphics card RAM store per-vertex data such as position and normal coordinates, color values, together with per-vertex attributes used by shader programs, such as sphere center point coordinates and radii. * All of these per-vertex VBO arrays for a particular type of primitive are activated and used in parallel by a VBO draw command such as glDrawElements or glMultiDrawElements. * Thus, although there will be (for example) the same radius for all parts of a sphere, it is replicated in the radius attribute array for all of the block of vertices of the polygonal GL object that is drawn to cover the shader sphere primitive. * For dynamic allocation of drawing primitives, it's best to pre-allocate VBO arrays in largish fixed-sized hunks for each primitive type and dole them out individually. 10,000 primitives may be a good VBO hunk size to use at first, minimizing the number of per-hunk draw calls. == IBOs == * IBOs (Index Buffer Objects) in graphics card RAM contain subscripts into the blocks of per-vertex data so that a large batch of allocated primitives may be drawn in one graphics call. One call will be needed for each hunk of primitives of a given type. * The indexed vertices make up a pattern of faces for each primitive (likely quads, triangles, or triangle-strips.) This is fast because it gets to transform and shade the vertices of a primitive in the graphics pipeline once, and re-use them for all of the faces that use the same vertex. == GlPrimitiveBuffer == * GLPrimitiveBuffer (through subtypes such as GLSphereBuffer) manages the data for a collection of hunks of objects of a particular primitive type. * It caches the Python (and possibly C/Numpy) numeric value arrays for each VBO, as well as a set of OpenGL handles in GLBufferObjects for accessing the VBO arrays (each one divided into hunks) in graphics card RAM. * Allocating a drawing primitive gives it a fixed vertex block ID that never changes. * The vertex block ID is an integer but not a subscript. It determines both the hunk number, and the offsets within the various VBO hunks to the blocks of vertex data for the primitive. * A vertex block contains data for a small sequence of vertices (e.g. a shader bounding box, tetrahedron, or billboard) that is the drawing pattern used to draw the primitive. * All vertex blocks for a given type are in 'unit' coordinates and are identical, so there is a common VBO for all hunks of vertices for primitives of a particular type. * Similarly, there is a common IBO for all hunks of indices for primitives of a particular type. Each copy of the vertex subscripting pattern is offset by adding the vertex block base subscript to all of the index values in the block. * The data for each primitive goes in a block of per-vertex attributes used by the shader programs. Each attribute memory slot contains four floating-point values. sphere primitives use only one slot: center point X, Y, Z coordinates with the radius in the W value. * Primitive block data values can be updated individually or in batches within a hunk-sized VBO array. * Primitive blocks may be deallocated and re-used quickly in groups, such as by a CSDL while regenerating the appearance of an NE1 model object. * Optimization: It's easy to monitor changes to the Python copy of a VBO hunk by keeping the low- and high-change subscripts. The before-drawing sync can send only the modified part of each hunk to a VBO sub-range in the graphics card RAM, or do nothing if there have been no changes. * During drawing, the per-primitive-type vertex shader program combines the unit primitive vertex coordinates from the vertex VBO with the primitive location (e.g. center point and radius.) The result is transformed into global modeling coordinates through the TransformControl matrix referred to by the transform_id attribute. * Any subset of the primitives in a particular VBO hunk can be drawn very quickly with a single glMultiDrawElements call, using the IBO indices managed by GLPrimitiveSets. * Any subset of primitives in the whole model can be drawn very quickly with a small number of glMultiDrawElements calls, no more than the number of active allocation hunks of each primitive type that needs to be drawn. """ import graphics.drawing.drawing_constants as drawing_constants from graphics.drawing.gl_buffers import GLBufferObject import numpy from OpenGL.GL import GL_ARRAY_BUFFER_ARB from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import GL_ELEMENT_ARRAY_BUFFER_ARB from OpenGL.GL import GL_FLOAT from OpenGL.GL import GL_QUADS from OpenGL.GL import GL_STATIC_DRAW from OpenGL.GL import GL_TEXTURE_2D #from OpenGL.GL import GL_TEXTURE0 from OpenGL.GL import GL_UNSIGNED_INT from OpenGL.GL import GL_VERTEX_ARRAY #from OpenGL.GL import glActiveTexture from OpenGL.GL import glBindTexture from OpenGL.GL import glDisable from OpenGL.GL import glDisableClientState from OpenGL.GL import glDrawElements from OpenGL.GL import glEnable from OpenGL.GL import glEnableClientState from OpenGL.GL import glVertexPointer # Pass an array of byte offsets into the graphics card index buffer object. from graphics.drawing.vbo_patch import glMultiDrawElementsVBO ##from OpenGL.GL.ARB.shader_objects import glUniform1iARB from OpenGL.GL.ARB.vertex_program import glDisableVertexAttribArrayARB from OpenGL.GL.ARB.vertex_program import glEnableVertexAttribArrayARB from OpenGL.GL.ARB.vertex_program import glVertexAttribPointerARB from utilities.debug_prefs import debug_pref, Choice_boolean_True # == # Constants. BYTES_PER_FLOAT = 4 # All per-vertex attributes are floats in GLSL. BYTES_PER_UINT = 4 # We use unsigned ints for vertex indices. HUNK_SIZE = 5000 # 10000 # 20000 # The number of primitives in each VBO hunk. # Note: if HUNK_SIZE is too large, it causes trouble in PyOpenGL or the GL driver # for unknown reasons. If too small, it causes more element draws than needed. # Russ determined a safe value by experiment (on Mac), at a time when the # "vertex replication" (which multiplies this to get actual number of # entries in the hunk arrays) was larger than it is now. Larger values # did not show performance speedup, and values this small did not show # a slowdown, on test cases with lots of spheres (more than 10k). # [bruce 090302 comment] # == def decodePrimID(ID): """ Decode primitive IDs into a Hunk number and an index within the Hunk. """ return (ID / HUNK_SIZE, ID % HUNK_SIZE) class GLPrimitiveBuffer(object): """ Manage VBO space for drawing primitives in large batches. """ # default values of instance variables transform_id_Hunks = None def __init__(self, shaderGlobals): """ Fill in the vertex VBO and IBO drawing pattern for this primitive type. @param shaderGlobals: the instance of class ShaderGlobals we will be associated with, used for its .shader and various related constants. """ # set localvars as follows, for the drawing pattern for VBOs/IBOs # for this primitive type: # # shader - The GLShaderObject to use. # # drawingMode - What kind of primitives to render, e.g. GL_QUADS. # # vertexBlock, indexBlock - Single blocks (lists) of vertices and indices # making up the drawing pattern for this primitive. # See description in the module docstrings for this class or its subclasses. if debug_pref("GLPane: use billboard primitives? (next session)", Choice_boolean_True, prefs_key = True ): drawingMode = GL_QUADS vertexBlock = shaderGlobals.billboardVerts indexBlock = shaderGlobals.billboardIndices pass else: drawingMode = GL_QUADS vertexBlock = shaderGlobals.shaderCubeVerts indexBlock = shaderGlobals.shaderCubeIndices pass # Remember the shader. self.shader = shader = shaderGlobals.shader # Shared data for drawing calls to follow. self.drawingMode = drawingMode # Remember the drawing pattern. (We may want to make transformed vertex # blocks someday, losing the one-hunk-per-type goodness in favor of some # other greater goodness like minimizing use of constant registers.) # See below for filling the vertex VBO and IBO with these. self.nVertices = len(vertexBlock) self.vertexBlock = vertexBlock self.indexBlock = indexBlock # Allocation of primitives within hunks. self.nPrims = 0 # Number of primitives allocated. self.freePrimSlotIDs = [] # Free list of freed primitives. self.nHunks = 0 # Number of hunks allocated. # Common per-vertex attribute hunk VBOs for all primitive types. # (The hunkVertVBO and hunkIndexIBO are shared by all hunks.) nVerts = self.nVertices self.colorHunks = HunkBuffer(shader, "color", nVerts, 4) self.glname_color_Hunks = HunkBuffer(shader, "glname_color", nVerts, 4) # Subclasses may add their own attributes to the hunkBuffers list, # beyond the ones we add here: self.hunkBuffers = [self.colorHunks, self.glname_color_Hunks, ] if shader.supports_transforms(): self.transform_id_Hunks = HunkBuffer(shader, "transform_id", nVerts, 1) self.hunkBuffers += [self.transform_id_Hunks] # Support for lazily updating drawing caches, namely a timestamp showing # when this GLPrimitiveBuffer was last flushed to graphics card RAM. self.flushed = drawing_constants.NO_EVENT_YET # Fill in shared data in the graphics card RAM. self._setupSharedVertexData() # Cached info for blocks of transforms. # Transforms here are lists (or Numpy arrays) of 16 numbers. self.transforms = [] self.identityTransform = ([1.0] + 4*[0.0]) * 3 + [1.0] return def color4(self,color): """ Minor helper function for colors. Converts a given (R, G, B) 3-tuple to (R, G, B, A) by adding an opacity of 1.0 . """ if len(color) == 3: # Add opacity to color if missing. color = (color[0], color[1], color[2], 1.0) pass return color def newPrimitives(self, n): """ Allocate a group of primitives. Returns a list of n IDs. """ primIDs = [] for i in range(n): # Take ones from the free list first. if len(self.freePrimSlotIDs): primID = self.freePrimSlotIDs.pop() else: # Allocate a new one. primID = self.nPrims # ID is a zero-origin subscript. self.nPrims += 1 # nPrims is a counter. # Allocate another set of hunks if the new ID has passed a hunk # boundary. if (primID + HUNK_SIZE) / HUNK_SIZE > self.nHunks: for buffer in self.hunkBuffers: buffer.addHunk() continue self.nHunks += 1 pass primIDs += [primID] continue return primIDs def releasePrimitives(self, idList): """ Release the given primitive IDs into the free-list. """ self.freePrimSlotIDs += idList return def _setupSharedVertexData(self): """ Gather data for the drawing pattern Vertex and Index Buffer Objects shared by all hunks of the same primitive type. The drawing pattern is replicated HUNK_SIZE times, and sent to graphics card RAM for use in every draw command for collections of primitives of this type. In theory, the vertex shader processes each vertex only once, even if it is indexed many times in different faces within the same draw. In practice, locality of vertex referencing in the drawing pattern is optimal, since there may be a cache of the most recent N transformed vertices in that stage of the drawing pipeline on graphics card. For indexed gl(Multi)DrawElements, the index is a list of faces (typically triangles or quads, specified by the drawingMode.) Each face is represented by a block of subscripts into the vertex block. For glMultiDrawElements, there is an additional pair of arrays that give offsets into blocks of the index block list, and the lengths of each block of indices. Because the index blocks are all the same length to draw individual primitives, we set up a single array containing a Hunk's worth of the index block length constant and use it for each Hunk draw. """ self.nIndices = len(self.indexBlock) * len(self.indexBlock[0]) indexOffset = 0 # (May cache these someday. No need now since they don't change.) Py_iboIndices = [] Py_vboVerts = [] for i in range(HUNK_SIZE): # Accumulate a hunk full of blocks of vertices. Each block is # identical, with coordinates relative to its local primitive # origin. Hence, the vertex VBO may be shared among all hunks of # primitives of the same type. A per-vertex attribute gives the # spatial location of the primitive origin, and is combined with the # local vertex coordinates in the vertex shader program. Py_vboVerts += self.vertexBlock # Accumulate a hunk full of index blocks, offsetting the indices in # each block to point to the vertices for the corresponding # primitive block in the vertex hunk. for face in self.indexBlock: Py_iboIndices += [idx + indexOffset for idx in face] continue indexOffset += self.nVertices continue # Push shared vbo/ibo hunk data through C to the graphics card RAM. C_vboVerts = numpy.array(Py_vboVerts, dtype=numpy.float32) self.hunkVertVBO = GLBufferObject( GL_ARRAY_BUFFER_ARB, C_vboVerts, GL_STATIC_DRAW) self.hunkVertVBO.unbind() C_iboIndices = numpy.array(Py_iboIndices, dtype=numpy.uint32) self.hunkIndexIBO = GLBufferObject( GL_ELEMENT_ARRAY_BUFFER_ARB, C_iboIndices, GL_STATIC_DRAW) self.hunkIndexIBO.unbind() # A Hunk-length of index block length constants for glMultiDrawElements. self.C_indexBlockLengths = numpy.array(HUNK_SIZE * [self.nIndices], dtype=numpy.uint32) return def draw(self, drawIndex = None, highlighted = False, selected = False, patterning = True, highlight_color = None, opacity = 1.0): """ Draw the buffered geometry, binding vertex attribute values for the shaders. If no drawIndex is given, the whole array is drawn. """ self.shader.setActive(True) # Turn on the chosen shader. glEnableClientState(GL_VERTEX_ARRAY) self.shader.setupDraw(highlighted, selected, patterning, highlight_color, opacity) # XXX No transform data until that is more implemented. ###self.shader.setupTransforms(self.transforms) # (note: the reason TransformControls work in their test case # is due to a manual call of shader.setupTransforms. [bruce 090306 guess]) if self.shader.get_TEXTURE_XFORMS(): # Activate a texture unit for transforms. ## XXX Not necessary for custom shader programs. ##glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.transform_memory) ### BUG: pylint warning: # Instance of 'GLPrimitiveBuffer' has no 'transform_memory' member #### REVIEW: should this be the attr of that name in GLShaderObject, # i.e. self.shader? I didn't fix it myself as a guess, in case other # uses of self also need fixing in the same way. [bruce 090304 comment] # Set the sampler to the handle for the active texture image (0). ## XXX Not needed if only one texture is being used? ##glActiveTexture(GL_TEXTURE0) ##glUniform1iARB(self.shader._uniform("transforms"), 0) pass glDisable(GL_CULL_FACE) # Draw the hunks. for hunkNumber in range(self.nHunks): # Bind the per-vertex generic attribute arrays for one hunk. for buffer in self.hunkBuffers: buffer.flush() # Sync graphics card copies of the VBO data. buffer.bindHunk(hunkNumber) continue # Shared vertex coordinate data VBO: GL_ARRAY_BUFFER_ARB. self.hunkVertVBO.bind() glVertexPointer(3, GL_FLOAT, 0, None) # Shared vertex index data IBO: GL_ELEMENT_ARRAY_BUFFER_ARB self.hunkIndexIBO.bind() if drawIndex is not None: # Draw the selected primitives for this Hunk. index = drawIndex[hunkNumber] primcount = len(index) glMultiDrawElementsVBO( self.drawingMode, self.C_indexBlockLengths, GL_UNSIGNED_INT, index, primcount) else: # For initial testing, draw all primitives in the Hunk. if hunkNumber < self.nHunks-1: nToDraw = HUNK_SIZE # Hunks before the last. else: nToDraw = self.nPrims - (self.nHunks-1) * HUNK_SIZE pass glDrawElements(self.drawingMode, self.nIndices * nToDraw, GL_UNSIGNED_INT, None) pass continue self.shader.setActive(False) # Turn off the chosen shader. glEnable(GL_CULL_FACE) self.hunkIndexIBO.unbind() # Deactivate the ibo. self.hunkVertVBO.unbind() # Deactivate all vbo's. glDisableClientState(GL_VERTEX_ARRAY) for buffer in self.hunkBuffers: buffer.unbindHunk() # glDisableVertexAttribArrayARB. continue return def makeDrawIndex(self, prims): """ Make a drawing index to be used by glMultiDrawElements on Hunk data. The return is a list of offset arrays, one for each Hunk of primitives. Each value in an offset array gives the *byte* offset in the IBO to the block of indices for a given primitive ID within the Hunk. """ hunkOffsets = [[] for i in range(self.nHunks)] # Collect the offsets to index blocks for individual primitives. for primID in prims: (hunk, index) = decodePrimID(primID) hunkOffsets[hunk] += [index * self.nIndices * BYTES_PER_UINT] continue # The indices for each hunk could be sorted here, which might go faster. # (But don't worry about it if drawing all primitives in random order is # as fast as the test that draws all primitives with glDrawElements.) # # The sorted offsets arrays could also be reduced to draw contiguous # runs of primitives, rather than single primitives. A list of run # lengths for each Hunk would have to be produced as well, rather than # using the shared list of constant lengths for individual primitives. # Push the offset arrays into C for faster use by glMultiDrawElements. C_hunkOffsets = [numpy.array(offset, dtype=numpy.uint32) for offset in hunkOffsets] return C_hunkOffsets pass # End of class GLPrimitiveBuffer. class HunkBuffer: """ Helper class to manage updates to Vertex Buffer Objects for groups of fixed-size HUNKS of per-vertex attributes in graphics card RAM. """ def __init__(self, shader, attribName, nVertices, nCoords): """ Allocate a Buffer Object for the hunk, but don't fill it in yet. attribName - String name of an attrib variable in the vertex shader. nVertices - The number of vertices in the primitive drawing pattern. nCoords - The number of coordinates per attribute (e.g. 1 for float, 3 for vec3, 4 for vec4), so the right size storage can be allocated. """ self.attribName = attribName self.nVertices = nVertices self.nCoords = nCoords self.hunks = [] # Look up the location of the named generic vertex attribute in the # previously linked shader program object. self.attribLocation = shader.attributeLocation(attribName) # Cache the Python data that will be sent to the graphics card RAM. # Internally, the data is a list, block-indexed by primitive ID, but # replicated in block sublists by a factor of self.nVertices to match # the vertex buffer. What reaches the attribute VBO is automatically # flattened into a sequence. self.data = [] return def addHunk(self): """ Allocate a new hunk VBO when needed. """ hunkNumber = len(self.hunks) self.hunks += [Hunk(hunkNumber, self.nVertices, self.nCoords)] return def bindHunk(self, hunkNumber): glEnableVertexAttribArrayARB(self.attribLocation) self.hunks[hunkNumber].VBO.bind() glVertexAttribPointerARB(self.attribLocation, self.nCoords, GL_FLOAT, 0, 0, None) return def unbindHunk(self): glDisableVertexAttribArrayARB(self.attribLocation) return def setData(self, primID, value): """ Add data for a primitive. The ID will always be within the array, or one past the end when allocating new ones. primID - In Python, this is just a subscript. value - The new data. """ # Internally, the data is a list, block-indexed by primitive ID, but # replicated in block sublists by a factor of self.nVertices to match # the vertex buffer size. What reaches the attribute VBO is # automatically flattened into a sequence of floats. replicatedValue = self.nVertices * [value] if primID >= len(self.data): assert primID == len(self.data) self.data += [replicatedValue] else: assert primID >= 0 self.data[primID] = replicatedValue pass self.changedRange(primID, primID+1) return def getData(self, primID): #bruce 090223 """ Inverse of setData. The ID must always be within the array. """ assert 0 <= primID < len(self.data) return self.data[primID][0] # Maybe a range setter would be useful, too: # def setDataRange(self, primLow, primHigh, valueList): def changedRange(self, chgLowID, chgHighID): """ Record a range of data changes, for later flushing. chgLowID and chgHighID are primitive IDs, possibly spanning many hunks. The high end is the index of the one *after* the end of the range, as usual in Python. Just passes it on to the relevant hunks for the range. """ (lowHunk, highHunk) = (chgLowID / HUNK_SIZE, (chgHighID - 1) / HUNK_SIZE) for hunk in self.hunks[lowHunk:highHunk+1]: hunk.changedRange(chgLowID, chgHighID) continue return def flush(self): """ Update a changed range of the data, sending it to the Buffer Objects in graphics card RAM. This level just passes the flush() on to the Hunks. """ for hunk in self.hunks: hunk.flush(self.data) pass # End of class HunkBuffer. class Hunk: """ Helper class to wrap low-level VBO objects with data caches, change ranges, and flushing of the changed range to the hunk VBO in graphics card RAM. """ def __init__(self, hunkNumber, nVertices, nCoords): """ hunkNumber - The index of this hunk, e.g. 0 for the first in a group. Specifies the range of IDs residing in this hunk. nVertices - The number of vertices in the primitive drawing pattern. nCoords - The number of entries per attribute, e.g. 1 for float, 3 for vec3, 4 for vec4, so the right size storage can be allocated. """ self.nVertices = nVertices self.hunkNumber = hunkNumber self.nCoords = nCoords self.VBO = GLBufferObject( GL_ARRAY_BUFFER_ARB, # Per-vertex attributes are all multiples (1-4) of Float32. HUNK_SIZE * self.nVertices * self.nCoords * BYTES_PER_FLOAT, GL_STATIC_DRAW) # Low- and high-water marks to optimize for sending a range of data. self.unchanged() return def unchanged(self): """ Mark a Hunk as unchanged. (Empty or flushed.) """ self.low = self.high = 0 return def changedRange(self, chgLowID, chgHighID): """ Record a range of data changes, for later flushing. chgLowID and chgHighID are primitive IDs, possibly spanning many hunks. The high end is the index of the one *after* the end of the range, as usual in Python. """ (lowHunk, lowIndex) = decodePrimID(chgLowID) (highHunk, highIndex) = decodePrimID(chgHighID) if self.hunkNumber < lowHunk or self.hunkNumber > highHunk: return # This hunk is not in the hunk range. if lowHunk < self.hunkNumber: self.low = 0 else: self.low = min(self.low, lowIndex) # Maybe extend the range. pass if highHunk > self.hunkNumber: self.high = HUNK_SIZE else: self.high = max(self.high, highIndex) # Maybe extend the range. pass return def flush(self, allData): """ Update a changed range of the data that applies to this hunk, sending it to the Buffer Object in graphics card RAM. allData - List of data blocks for the whole hunk-list. We'll extract just the part relevant to the changed part of this particular hunk. Internally, the data is a list, block-indexed by primitive ID, but replicated in block sublists by a factor of self.nVertices to match the vertex buffer size. What reaches the attribute VBO is automatically flattened into a sequence. """ rangeSize = self.high - self.low assert rangeSize >= 0 if rangeSize == 0: # Nothing to do. return lowID = (self.hunkNumber * HUNK_SIZE) + self.low highID = (self.hunkNumber * HUNK_SIZE) + self.high # Send all or part of the Python data to C. C_data = numpy.array(allData[lowID:highID], dtype=numpy.float32) if rangeSize == HUNK_SIZE: # Special case to send the whole Hunk's worth of data. self.VBO.updateAll(C_data) else: # Send a portion of the HunkBuffer, with byte offset within the VBO. # (Per-vertex attributes are all multiples (1-4) of Float32.) offset = self.low * self.nVertices * self.nCoords * BYTES_PER_FLOAT self.VBO.update(offset, C_data) pass self.unchanged() # Now we're in sync. return pass # End of class HunkBuffer.
NanoCAD-master
cad/src/graphics/drawing/GLPrimitiveBuffer.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ drawcompass.py @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. bruce 080910 factored this out of class GLPane's drawcompass method bruce 081015 put constant parts into a display list (possible speedup), and created class Compass to make this easier """ from utilities.prefs_constants import UPPER_RIGHT from utilities.prefs_constants import UPPER_LEFT from utilities.prefs_constants import LOWER_LEFT from OpenGL.GL import glMatrixMode from OpenGL.GL import GL_MODELVIEW from OpenGL.GL import GL_PROJECTION from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GL import glLoadIdentity from OpenGL.GL import glOrtho from OpenGL.GL import glRotatef from OpenGL.GL import GL_COLOR_MATERIAL from OpenGL.GL import glEnable from OpenGL.GL import glDisable from OpenGL.GL import GL_CULL_FACE from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_DEPTH_TEST from OpenGL.GL import glPolygonMode from OpenGL.GL import glColorMaterial from OpenGL.GL import GL_FRONT_AND_BACK, GL_FILL, GL_AMBIENT_AND_DIFFUSE from OpenGL.GL import glGenLists from OpenGL.GL import glNewList from OpenGL.GL import GL_COMPILE from OpenGL.GL import glEndList from OpenGL.GL import glCallList try: from OpenGL.GLE import glePolyCone except: print "GLE module can't be imported. Now trying _GLE" from OpenGL._GLE import glePolyCone from PyQt4.Qt import QFont, QString, QColor import math # == # drawing parameters # (note: most of them are hardcoded into specific routines) _P4 = 3.8 # ??? may be used to specify the slant of the arrow head (conical portion).? # == class Compass(object): def __init__(self, glpane): """ @param glpane: typically a QGLWidget; used only for its methods glpane.qglColor and glpane.renderText. @warning: the right OpenGL display list context must be current when this constructor is called. """ self.glpane = glpane self._compass_dl = glGenLists(1) glNewList(self._compass_dl, GL_COMPILE) _draw_compass_geometry() glEndList() self._font = QFont( QString("Helvetica"), 12) return def draw(self, aspect, quat, compassPosition, compass_moved_in_from_corner, displayCompassLabels ): """ Draw the "compass" (the perpendicular colored arrows showing orientation of model coordinates) in the specified corner of the GLPane (self.glpane). Doesn't assume a specific glMatrixMode; sets it to GL_MODELVIEW on exit. Doesn't trash either matrix, but does require enough GL_PROJECTION stack depth to do glPushMatrix on it (though the guaranteed depth for that stack is only 2). """ glpane = self.glpane #bruce 050608 improved behavior re GL state requirements and side effects; # 050707 revised docstring accordingly. #mark 0510230 switched Y and Z colors. # Now X = red, Y = green, Z = blue, standard in all CAD programs. glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() # needed! # Set compass position using glOrtho if compassPosition == UPPER_RIGHT: # hack for use in testmode [revised bruce 070110 when GLPane_overrider merged into GLPane]: if compass_moved_in_from_corner: glOrtho(-40 * aspect, 15.5 * aspect, -50, 5.5, -5, 500) else: glOrtho(-50 * aspect, 3.5 * aspect, -50, 4.5, -5, 500) # Upper Right elif compassPosition == UPPER_LEFT: glOrtho(-3.5 * aspect, 50.5 * aspect, -50, 4.5, -5, 500) # Upper Left elif compassPosition == LOWER_LEFT: glOrtho(-3.5 * aspect, 50.5 * aspect, -4.5, 50.5, -5, 500) # Lower Left else: glOrtho(-50 * aspect, 3.5 * aspect, -4.5, 50.5, -5, 500) # Lower Right glRotatef(quat.angle * 180.0/math.pi, quat.x, quat.y, quat.z) glCallList(self._compass_dl) ##Adding "X, Y, Z" text labels for Axis. By test, the following code will get # segmentation fault on Mandrake Linux 10.0 with libqt3-3.2.3-17mdk # or other 3.2.* versions, but works with libqt3-3.3.3-26mdk. Huaicai 1/15/05 if displayCompassLabels: # maybe todo: optimize by caching QString, QColor objects during __init__ glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) ## glPushMatrix() font = self._font glpane.qglColor(QColor(200, 75, 75)) # Dark Red glpane.renderText(_P4, 0.0, 0.0, QString("x"), font) glpane.qglColor(QColor(25, 100, 25)) # Dark Green glpane.renderText(0.0, _P4, 0.0, QString("y"), font) glpane.qglColor(QColor(50, 50, 200)) # Dark Blue glpane.renderText(0.0, 0.0, _P4 + 0.2, QString("z"), font) ## glPopMatrix() glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) # note: this leaves ending matrixmode in standard state, GL_MODELVIEW # (though it doesn't matter for present calling code; see discussion in bug 727) glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) glPopMatrix() return # from draw pass # end of class Compass # == def _draw_compass_geometry(): """ Do GL state changes and draw constant geometry for compass. Doesn't depend on any outside state, so can be compiled into an unchanging display list. """ glEnable(GL_COLOR_MATERIAL) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glDisable(GL_CULL_FACE) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) #ninad 070122 - parametrized the compass drawing. (also added some doc). #Also reduced the overall size of the compass. p1 = -1 # ? start point of arrow cyl? p2 = 3.25 #end point of the arrow cylindrical portion p3 = 2.5 #arrow head start point p5 = 4.5 # cone tip r1 = 0.2 #cylinder radius r2 =0.2 r3 = 0.2 r4 = 0.60 #cone base radius glePolyCone([[p1,0,0], [0,0,0], [p2,0,0], [p3,0,0], [_P4,0,0], [p5,0,0]], [[0,0,0], [1,0,0], [1,0,0], [.5,0,0], [.5,0,0], [0,0,0]], [r1,r2,r3,r4,0,0]) glePolyCone([[0,p1,0], [0,0,0], [0,p2,0], [0,p3,0], [0,_P4,0], [0,p5,0]], [[0,0,0], [0,.9,0], [0,.9,0], [0,.4,0], [0,.4,0], [0,0,0]], [r1,r2,r3,r4,0,0]) glePolyCone([[0,0,p1], [0,0,0], [0,0,p2], [0,0,p3], [0,0,_P4], [0,0,p5]], [[0,0,0], [0,0,1], [0,0,1], [0,0,.4], [0,0,.4], [0,0,0]], [r1,r2,r3,r4,0,0]) glEnable(GL_CULL_FACE) glDisable(GL_COLOR_MATERIAL) return # end
NanoCAD-master
cad/src/graphics/drawing/drawcompass.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ gl_buffers.py - OpenGL data buffer objects. @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originated by Josh as drawer.py . Various developers extended it since then. Brad G. added ColorSorter features. At some point Bruce partly cleaned up the use of display lists. 071030 bruce split some functions and globals into draw_grid_lines.py and removed some obsolete functions. 080210 russ Split the single display-list into two second-level lists (with and without color) and a set of per-color sublists so selection and hover-highlight can over-ride Chunk base colors. ColorSortedDisplayList is now a class in the parent's displist attr to keep track of all that stuff. 080311 piotr Added a "drawpolycone_multicolor" function for drawing polycone tubes with per-vertex colors (necessary for DNA display style) 080313 russ Added triangle-strip icosa-sphere constructor, "getSphereTriStrips". 080420 piotr Solved highlighting and selection problems for multi-colored objects (e.g. rainbow colored DNA structures). 080519 russ pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py """ import graphics.drawing.drawing_constants as drawing_constants # Vertex Buffer Object (VBO) and Index Buffer Object (IBO) support. # For docs see http://www.opengl.org/sdk/docs/man/xhtml/glBufferData.xml . # Notice that the ARB-suffixed versions of the OpenGL calls are used here. # They're the ones with PyConvert ctypes wrappers, see: (the incomprehensible) # http://pyopengl.sourceforge.net/ctypes/pydoc/ # OpenGL.GL.ARB.vertex_buffer_object.html # The sources will do you more good. Also see "Array Handling Routines" here: # http://pyopengl.sourceforge.net/documentation/opengl_diffs.html # from OpenGL.GL.ARB.vertex_buffer_object import glGenBuffersARB from OpenGL.GL.ARB.vertex_buffer_object import glDeleteBuffersARB if 0: from OpenGL.GL.ARB.vertex_buffer_object import glBufferDataARB from OpenGL.GL.ARB.vertex_buffer_object import glBufferSubDataARB else: # Patched versions. from graphics.drawing.vbo_patch import glBufferDataARB, glBufferSubDataARB # Unwrappered. from OpenGL.raw.GL.ARB.vertex_buffer_object import glBindBufferARB # Use with a size in bytes and a data of None to allocate a block of space. from OpenGL.raw.GL.ARB.vertex_buffer_object import glBufferDataARB as glAllocBufferData class GLBufferObject(object): """ Buffer data in the graphics card's RAM space. This is a thin wrapper that helps use the OpenGL functions. Useful man pages for glBind, glBufferData, etc. for OpenGL 2.1 are at: http://www.opengl.org/sdk/docs/man PyOpenGL versions are at: http://pyopengl.sourceforge.net/ctypes/pydoc/OpenGL.html 'target' is GL_ARRAY_BUFFER_ARB for vertex/normal buffers (VBO's), and GL_ELEMENT_ARRAY_BUFFER_ARB for index buffers (IBO's.) 'data' is a numpy.array, with dtype=numpy.<datatype>, or a single number giving the size *in bytes*, to allocate the space but not yet fill it in . 'usage' is one of the hint constants, like GL_STATIC_DRAW. """ def __init__(self, target, data, usage): self.buffer = glGenBuffersARB(1) # Returns a numpy.ndarray for > 1. self.target = target # OpenGL array binding target. self.usage = usage # OpenGL Buffer Object usage hint. self.bind() if type(data) == type(1): self.size = data # Allocate with glBufferDataARB but don't fill it in yet. glAllocBufferData(target, self.size, None, usage) else: self.size = len(data) # Allocate, and push the data over to Graphics card RAM too. glBufferDataARB(target, data, usage) self.unbind() # Support for lazily updating drawing caches, namely a # timestamp showing when this GLBufferObject was last flushed. self.flushed = drawing_constants.NO_EVENT_YET return def updateAll(self, data): """ Update the contents of a buffer with glBufferData. """ self.bind() # Strangely, this does not show the problem that glBufferSubDataARB does. glBufferDataARB(self.target, data, self.usage) self.unbind() return def update(self, offset, data): """ Update the contents of a buffer with glBufferSubData. The offset into the buffer is *in bytes*! """ self.bind() ## Warning! This call on glBufferSubDataARB sometimes hangs MacOS in ## the "Spinning Ball of Death" and can't be killed, when the data array ## is getting big (larger than 320,000 bytes for 100x100 sphere radii, ## 10,000 spheres * 4 bytes per radius * 8 vertices per box.) # XXX Should break up the transfer into batches here, similar to what is # done with large batches of texture memory matrices. # XXX Need to determine the array element size. Assume 4 for now. glBufferSubDataARB(self.target, offset, data) self.unbind() return def __del__(self): """ Delete a GLBufferObject. We don't expect that there will be a lot of deleting of GLBufferObjects, but don't want them to sit on a lot of graphics card RAM if we did. """ # Since may be too late to clean up buffer objects through the Graphics # Context while exiting, we trust that OpenGL or the device driver will # deallocate the graphics card RAM when the Python process exits. try: glDeleteBuffersARB(1, [self.buffer]) except: ##print "Exception in glDeleteBuffersARB." pass return def bind(self): """ Have to bind a particular buffer to its target to fill or draw from it. Don't forget to unbind() it! """ glBindBufferARB(self.target, self.buffer) return def unbind(self): """ Unbind a buffer object from its target after use. Failure to do this can kill Python on some graphics platforms! """ glBindBufferARB(self.target, 0) return pass # End of class GLBufferObject.
NanoCAD-master
cad/src/graphics/drawing/gl_buffers.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ gl_shaders.py - OpenGL shader objects. For shader concepts and links, see the Wikipedia introductions at: http://en.wikipedia.org/wiki/GLSL http://en.wikipedia.org/wiki/Graphics_pipeline The GLSL quick reference card and language specification in PDF are useful: http://www.mew.cx/glsl_quickref.pdf http://www.opengl.org/registry/doc/GLSLangSpec.Full.1.20.8.pdf Some details about different "shader models", i.e. versions of the "GPU assembly language" behind GLSL: http://en.wikipedia.org/wiki/Comparison_of_ATI_graphics_processing_units#DirectX_version_note http://en.wikipedia.org/wiki/Shader_Model_3#Shader_model_comparison For the OpenGL interface, see the API man pages and ARB specifications: http://www.opengl.org/sdk/docs/man/ http://oss.sgi.com/projects/ogl-sample/registry/ARB/vertex_shader.txt http://oss.sgi.com/projects/ogl-sample/registry/ARB/fragment_shader.txt http://oss.sgi.com/projects/ogl-sample/registry/ARB/shader_objects.txt Useful man pages for OpenGL 2.1 are at: http://www.opengl.org/sdk/docs/man PyOpenGL versions are at: http://pyopengl.sourceforge.net/ctypes/pydoc/OpenGL.html @author: Russ Fish @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Russ 081002: Added some Transform state to GLSphereShaderObject, and code to notice when there is not enough constant memory for a matrix block there. Added get_TEXTURE_XFORMS() and get_N_CONST_XFORMS() methods. Moved GLSphereBuffer to its own file. Much of its code goes to the new superclass, GLPrimitiveBuffer, and its helper classes HunkBuffer and Hunk. The setupTransforms() method stays in GLSphereShaderObject. updateRadii() and sendRadii() disappeared, subsumed into the GLPrimitiveBuffer Hunk logic. In the sphere vertex shader, I combined center_pt and radius per-vertex attributes into one center_rad vec4 attribute, rather than using two vec4's worth of VBO memory, and added opacity to the color, changing it from a vec3 to a vec4. Drawing pattern vertices are now relative to the center_pt and scaled by the radius attributes, handled by the shader. Russ 090116: Factored GLShaderObject out of GLSphereShaderObject, and added GLCylinderShaderObject. The only difference between them at this level is the GLSL source passed in during initialization. """ # Whether to use texture memory for transforms, or a uniform array of mat4s, # or neither (no support for transforms). TEXTURE_XFORMS = False UNIFORM_XFORMS = False assert not (TEXTURE_XFORMS and UNIFORM_XFORMS) SUPPORTS_XFORMS = TEXTURE_XFORMS or UNIFORM_XFORMS # Note [bruce 090306]: Current code never uses TransformControl, so I revised # things to permit turning off both kinds of transform support, and I'm doing # that now in case it improves anything on any graphics cards to leave out the # associated GLSL code. (We still have a tiny bit of GLSL code and one extra # uniform which are not needed when transforms are not supported. # That would be easy to clean up, but is not important for now.) # When UNIFORM_XFORMS, use a fixed-sized block of uniform memory for transforms. # (This is a max, refined using GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB later.) N_CONST_XFORMS = 270 # (Gets CPU bound at 275. Dunno why.) # Used in fine-tuning N_CONST_XFORMS to leave room for other GPU vars and temps. # If you increase the complexity of the vertex shader program a little bit, and # rendering slows down by 100x, maybe you ran out of room. Try increasing this. _VERTEX_SHADER_GPU_VAR_SLACK = 110 # Turns on a debug info message. CHECK_TEXTURE_XFORM_LOADING = False # True ## Never check in a True value. # # Note: due to an OpenGL or PyOpengl Bug, can't read back huge transform # textures due to SIGSEGV killing Python in glGetTexImage. # # Traceback on MacOS 10.5.2 with 2178 transforms: # Exception Type: EXC_BAD_ACCESS (SIGSEGV) # Exception Codes: KERN_INVALID_ADDRESS at 0x00000000251f5000 # Thread 0 Crashed: # 0 libSystem.B.dylib 0xffff0884 __memcpy + 228 # 1 libGLImage.dylib 0x913e8ac6 glgProcessPixelsWithProcessor + 326 # 2 GLEngine 0x1e9dbace glGetTexImage_Exec + 1534 # 3 libGL.dylib 0x9170dd4f glGetTexImage + 127 # # And while we're on the subject, there is a crash that kills Python while # *writing* matrices to graphics card RAM. I suspect that libGLImage is running # out of texture memory space. I've looked for a method to verify that there is # enough left, but have not found one. Killing a bloated FireFox has helped. # # Traceback on MacOS 10.5.2 with only 349 transforms requested in this case. # Exception Type: EXC_BAD_ACCESS (SIGSEGV) # Exception Codes: KERN_INVALID_ADDRESS at 0x0000000013b88000 # Thread 0 Crashed: # 0 libSystem.B.dylib 0xffff08a0 __memcpy + 256 # 1 libGLImage.dylib 0x913ea5e9 glgCopyRowsWithMemCopy( # GLGOperation const*, unsigned long, GLDPixelMode const*) + 121 # 2 libGLImage.dylib 0x913e8ac6 glgProcessPixelsWithProcessor + 326 # 3 GLEngine 0x1ea16198 gleTextureImagePut + 1752 # 4 GLEngine 0x1ea1f896 glTexSubImage2D_Exec + 1350 # 5 libGL.dylib 0x91708cdb glTexSubImage2D + 155 from geometry.VQT import A, norm import utilities.EndUser as EndUser from graphics.drawing.sphere_shader import sphereVertSrc, sphereFragSrc from graphics.drawing.cylinder_shader import cylinderVertSrc, cylinderFragSrc from graphics.drawing.patterned_drawing import isPatternedDrawing import foundation.env as env from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import hoverHighlightingColorStyle_prefs_key from utilities.prefs_constants import HHS_SOLID, HHS_HALO from utilities.prefs_constants import selectionColor_prefs_key from utilities.prefs_constants import selectionColorStyle_prefs_key from utilities.prefs_constants import SS_SOLID, SS_HALO from utilities.prefs_constants import haloWidth_prefs_key from utilities.debug_prefs import debug_pref from utilities.debug_prefs import Choice_boolean_False, Choice_boolean_True import numpy from OpenGL.GL import GL_FLOAT from OpenGL.GL import GL_FRAGMENT_SHADER from OpenGL.GL import GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB #from OpenGL.GL import GL_NEAREST from OpenGL.GL import GL_RGBA from OpenGL.GL import GL_RGBA32F_ARB from OpenGL.GL import GL_TEXTURE_2D #from OpenGL.GL import GL_TEXTURE_MAG_FILTER #from OpenGL.GL import GL_TEXTURE_MIN_FILTER from OpenGL.GL import GL_TRUE from OpenGL.GL import GL_VERTEX_SHADER from OpenGL.GL import GL_VALIDATE_STATUS from OpenGL.GL import glBindTexture #from OpenGL.GL import glEnable from OpenGL.GL import glGenTextures from OpenGL.GL import glGetInteger from OpenGL.GL import glGetTexImage from OpenGL.GL import glTexImage2D from OpenGL.GL import glTexSubImage2D ### Substitute the PyOpenGL 3.0.0b3 versions, which work on Windows as well as MacOS. ##from OpenGL.GL.ARB.shader_objects import glAttachObjectARB ##from OpenGL.GL.ARB.shader_objects import glCompileShaderARB ##from OpenGL.GL.ARB.shader_objects import glCreateProgramObjectARB ##from OpenGL.GL.ARB.shader_objects import glCreateShaderObjectARB ##from OpenGL.GL.ARB.shader_objects import glGetInfoLogARB ##from OpenGL.GL.ARB.shader_objects import glGetObjectParameterivARB ##from OpenGL.GL.ARB.shader_objects import glGetUniformLocationARB ##from OpenGL.GL.ARB.shader_objects import glGetUniformivARB ##from OpenGL.GL.ARB.shader_objects import glLinkProgramARB ##from OpenGL.GL.ARB.shader_objects import glShaderSourceARB ##from OpenGL.GL.ARB.shader_objects import glUniform1fARB ##from OpenGL.GL.ARB.shader_objects import glUniform1iARB ##from OpenGL.GL.ARB.shader_objects import glUniform3fvARB ##from OpenGL.GL.ARB.shader_objects import glUniform4fvARB ##from OpenGL.GL.ARB.shader_objects import glUniformMatrix4fvARB ##from OpenGL.GL.ARB.shader_objects import glUseProgramObjectARB ##from OpenGL.GL.ARB.shader_objects import glValidateProgramARB ##from OpenGL.GL.ARB.vertex_shader import glGetAttribLocationARB from graphics.drawing.shader_objects_patch import glAttachObjectARB from graphics.drawing.shader_objects_patch import glCompileShaderARB from graphics.drawing.shader_objects_patch import glCreateProgramObjectARB from graphics.drawing.shader_objects_patch import glCreateShaderObjectARB from graphics.drawing.shader_objects_patch import glGetInfoLogARB from graphics.drawing.shader_objects_patch import glGetObjectParameterivARB from graphics.drawing.shader_objects_patch import glGetUniformLocationARB from graphics.drawing.shader_objects_patch import glGetUniformivARB from graphics.drawing.shader_objects_patch import glLinkProgramARB from graphics.drawing.shader_objects_patch import glShaderSourceARB from graphics.drawing.shader_objects_patch import glUniform1fARB from graphics.drawing.shader_objects_patch import glUniform1iARB from graphics.drawing.shader_objects_patch import glUniform3fvARB from graphics.drawing.shader_objects_patch import glUniform4fvARB from graphics.drawing.shader_objects_patch import glUniformMatrix4fvARB from graphics.drawing.shader_objects_patch import glUseProgramObjectARB from graphics.drawing.shader_objects_patch import glValidateProgramARB from graphics.drawing.vertex_shader_patch import glGetAttribLocationARB _warnedVars = {} # Drawing_style constants. DS_NORMAL = 0 DS_OVERRIDE_COLOR = 1 DS_PATTERN = 2 DS_HALO = 3 class GLShaderObject(object): """ Base class for managing OpenGL shaders. """ # default values of per-subclass constants _has_uniform_debug_code = False # whether this shader has the uniform variable 'debug_code' # (a boolean which enables debug behavior) # (it might be better to set this by asking OpenGL whether # that uniform exists, after loading the shader source) # initial values of instance variables error = False # set for shader creation/compilation error _active = False # whether this is GL's current shader now # Cached info for blocks of transforms. n_transforms = None # Size of the block. transform_memory = None # Texture memory handle. def __init__(self, shaderName, shaderVertSrc, shaderFragSrc): # note: on any error, we set self.error, print a message, and return. # exceptions will be caught by caller and also set self.error, # but result in less specific printed error messages. # Configure the max constant RAM used for a "uniform" transforms block. if UNIFORM_XFORMS: global N_CONST_XFORMS oldNCX = N_CONST_XFORMS maxComponents = glGetInteger(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB) N_CONST_XFORMS = min( N_CONST_XFORMS, # Each matrix has 16 components. Leave slack for other vars too. (maxComponents - _VERTEX_SHADER_GPU_VAR_SLACK) / 16) if N_CONST_XFORMS <= 0: print ( "N_CONST_XFORMS not positive, is %d. %d max components." % (N_CONST_XFORMS, maxComponents)) # Now, we think this means we should use display lists instead. print "error: not enough shader constant memory" self.error = True return elif N_CONST_XFORMS == oldNCX: print ("N_CONST_XFORMS unchanged at %d. %d max components." % (N_CONST_XFORMS, maxComponents)) else: print ( "N_CONST_XFORMS changed to %d, was %d. %d max components." % (N_CONST_XFORMS, oldNCX, maxComponents)) pass pass # Version statement has to come first in GLSL source. prefix = """// requires GLSL version 1.20 #version 120 """ # Insert preprocessor constants before both shader source code strings # (using a constant number of lines, to preserve GLSL line numbers) if UNIFORM_XFORMS: prefix += "#define UNIFORM_XFORMS\n" prefix += "#define N_CONST_XFORMS %d\n" % N_CONST_XFORMS elif TEXTURE_XFORMS: prefix += "#define TEXTURE_XFORMS\n" prefix += "\n" else: prefix += "\n\n" pass # GLSL on the nVidia GeForce 7000 only supports constant array # subscripts, and subscripting by a loop index variable. if not debug_pref("GLPane: shaders with only constant subscripts?", Choice_boolean_True, prefs_key = True): prefix += "#define FULL_SUBSCRIPTING\n" else: prefix += "\n" # To keep the shader line numbers unchanged. pass if debug_pref("GLPane: simulate GLSL syntax error (next session)", Choice_boolean_False, prefs_key = True): prefix += "}\n" # remove whitespace before and after each prefix line [bruce 090306] prefix = '\n'.join( [line.strip() for line in prefix.split('\n')] ) assert prefix[-1] == '\n' # Pass the source strings to the shader compiler. self.vertShader = self.createShader(shaderName, GL_VERTEX_SHADER, prefix + shaderVertSrc) self.fragShader = self.createShader(shaderName, GL_FRAGMENT_SHADER, prefix + shaderFragSrc) if self.error: # May be set by createShader. return # Can't do anything good after an error. # Link the compiled shaders into a shader program. self.progObj = glCreateProgramObjectARB() glAttachObjectARB(self.progObj, self.vertShader) glAttachObjectARB(self.progObj, self.fragShader) try: glLinkProgramARB(self.progObj) # Checks status, raises error if bad. except: self.error = True print shaderName, "shader program link error" print glGetInfoLogARB(self.progObj) return # Can't do anything good after an error. # Optional, may be useful for debugging. glValidateProgramARB(self.progObj) status = glGetObjectParameterivARB(self.progObj, GL_VALIDATE_STATUS) if (not status): self.error = True print "Shader program validation error" print glGetInfoLogARB(self.progObj) return # Can't do anything good after an error. return def createShader(self, shaderName, shaderType, shaderSrc): """ Create, load, and compile a shader. """ shader = glCreateShaderObjectARB(shaderType) glShaderSourceARB(shader, shaderSrc) try: glCompileShaderARB(shader) # Checks status, raises error if bad. except: self.error = True types = {GL_VERTEX_SHADER:"vertex", GL_FRAGMENT_SHADER:"fragment"} print ("\n%s %s shader program compilation error" % (shaderName, types[shaderType])) print glGetInfoLogARB(shader) pass return shader def configShader(self, glpane): """ Fill in uniform variables in the shader self, before using it to draw. @param glpane: The current glpane, containing NE1 graphics context information related to the drawing environment. This is used to find proper values for uniform variables we set in the shader. """ # Can't do anything good after an error loading the shader programs. if self.error: return # Shader needs to be active to set uniform variables. wasActive = self._active if not wasActive: self.setActive(True) pass # Debugging control. if self._has_uniform_debug_code: # review: use _has_uniform("debug_code") instead? glUniform1iARB( self._uniform("debug_code"), int(debug_pref("GLPane: shader debug graphics?", Choice_boolean_False, prefs_key = True))) # Default override_opacity, multiplies the normal color alpha component. glUniform1fARB(self._uniform("override_opacity"), 1.0) # Russ 081208: Consider caching the glpane pointer. GLPane_minimal # inherits from QGLWidget, which includes the OpenGL graphics context. # Currently we share 'display list context' and related information # across two kinds of OpenGL contexts, the main GLPane and the # ThumbViews used to select atom types, show clipboard parts, and maybe # more. In the future it may be more complicated. Then we may need to # be more specific about accounting for what's in particular contexts. # XXX Hook in full NE1 lighting scheme and material settings. # Material is [ambient, diffuse, specular, shininess]. glUniform4fvARB(self._uniform("material"), 1, [0.3, 0.6, 0.5, 20.0]) glUniform1iARB(self._uniform("perspective"), (1, 0)[glpane.ortho]) # See GLPane._setup_projection(). vdist = glpane.vdist # See GLPane_minimal.setDepthRange_Normal(). near = vdist * (glpane.near + glpane.DEPTH_TWEAK) far = vdist * glpane.far glUniform4fvARB(self._uniform("clip"), 1, [near, far, 0.5*(far + near), 1.0/(far - near)]) # The effect of setDepthRange_Highlighting() is done as the shaders # set the gl_FragDepth during a highlighted drawing style. glUniform1fARB(self._uniform("DEPTH_TWEAK"), glpane.DEPTH_TWEAK) # Pixel width of window for halo drawing calculations. self.window_width = glpane.width # Single light for now. # XXX Get NE1 lighting environment state. glUniform4fvARB(self._uniform("intensity"), 1, [1.0, 0.0, 0.0, 0.0]) light0 = A([-1.0, 1.0, 1.0]) glUniform3fvARB(self._uniform("light0"), 1, light0) # Blinn shading highlight vector, halfway between the light and the eye. eye = A([0.0, 0.0, 1.0]) halfway0 = norm((eye + light0) / 2.0) glUniform3fvARB(self._uniform("light0H"), 1, halfway0) if not wasActive: self.setActive(False) return def setupDraw(self, highlighted = False, selected = False, patterning = True, highlight_color = None, opacity = 1.0): """ Set up for hover-highlighting and selection drawing styles. There is similar code in CSDL.draw(), which has similar arguments. XXX Does Solid and halo now, need to implement patterned drawing too. """ # Shader needs to be active to set uniform variables. wasActive = self._active if not wasActive: self.setActive(True) pass patterned_highlighting = (False and # XXX patterning and isPatternedDrawing(highlight = highlighted)) # note: patterned_highlighting variable is not yet used here [bruce 090304 comment] halo_selection = (selected and env.prefs[selectionColorStyle_prefs_key] == SS_HALO) halo_highlighting = (highlighted and env.prefs[hoverHighlightingColorStyle_prefs_key] == HHS_HALO) # Halo drawing style is used for hover-highlighing and halo-selection. drawing_style = DS_NORMAL # Solid drawing by default. if halo_highlighting or halo_selection: drawing_style = DS_HALO # Halo drawing was first implemented with wide-line drawing, which # extends to both sides of the polygon edge. The halo is actually # half the wide-line width that is specified by the setting. # XXX The setting should be changed to give the halo width instead. halo_width = env.prefs[haloWidth_prefs_key] / 2.0 # The halo width is specified in viewport pixels, as is the window # width the viewport transform maps onto. In post-projection and # clipping normalized device coords (+-1), it's a fraction of the # window half-width of 1.0 . ndc_halo_width = halo_width / (self.window_width / 2.0) glUniform1fARB(self._uniform("ndc_halo_width"), ndc_halo_width) elif highlighted or selected: drawing_style = DS_NORMAL # Non-halo highlighting or selection. glUniform1iARB(self._uniform("drawing_style"), drawing_style) # Color for selection or highlighted drawing. override_color = None if highlighted: if highlight_color is None: # Default highlight color. override_color = env.prefs[hoverHighlightingColor_prefs_key] else: # Highlight color passed as an argument. override_color = highlight_color elif selected: override_color = env.prefs[selectionColor_prefs_key] pass if override_color: if len(override_color) == 3: override_color += (opacity,) pass glUniform4fvARB(self._uniform("override_color"), 1, override_color) pass if not wasActive: self.setActive(False) pass return def setPicking(self, tf): """ Controls glnames-as-color drawing mode for mouseover picking. There seems to be no way to access the GL name stack in shaders. Instead, for mouseover, draw shader primitives with glnames as colors in glRenderMode(GL_RENDER), then read back the pixel color (glname) and depth value. @param tf: Boolean, draw glnames-as-color if True. """ # Shader needs to be active to set uniform variables. wasActive = self._active if not wasActive: self.setActive(True) pass glUniform1iARB(self._uniform("draw_for_mouseover"), int(tf)) if not wasActive: self.setActive(False) pass return def _has_uniform(self, name): #bruce 090309 """ @return: whether the specified uniform (input) shader variable has a location. @rtype: boolean @note: this can differ for different platforms based on the level of optimization done by their implementation of GLSL (if the uniform is allocated but not used by our shaders). @see: _uniform """ loc = glGetUniformLocationARB(self.progObj, name) return (loc != -1) def _uniform(self, name): #bruce 090302 renamed from self.uniform() """ Return location of a uniform (input) shader variable. If it's not found, return -1 and warn once per session for end users, or raise an AssertionError for developers. @see: _has_uniform """ loc = glGetUniformLocationARB(self.progObj, name) if loc == -1: # The glGetUniformLocationARB man page says: # "name must be an active uniform variable name in program that is # not a structure, an array of structures, or a subcomponent of a # vector or a matrix." # # It "returns -1 if the name does not correspond to an active # uniform variable in program". Then getUniform ignores it: "If # location is equal to -1, the data passed in will be silently # ignored and the specified uniform variable will not be changed." # # Lets not be so quiet. msg = "Invalid or unused uniform shader variable name '%s'." % name if EndUser.enableDeveloperFeatures(): # Developers want to know of a mismatch between their Python # and shader programs as soon as possible. Not doing so causes # logic errors, or at least incorrect assumptions, to silently # propagate through the code and makes debugging more difficult. assert 0, msg else: # End users on the other hand, may value program stability more. # Just print a warning if the program is released. Do it only # once per session, since this will be in the inner draw loop! global _warnedVars if name not in _warnedVars: print "Warning:", msg _warnedVars += [name] pass pass pass return loc def getUniformInt(self, name): """ Return value of a uniform (input) shader variable. """ return glGetUniformivARB(self.progObj, self._uniform(name)) def _has_shader_attribute(self, name): #bruce 090309 [untested, not currently used] """ @return: whether the specified attribute (per-vertex input) shader variable has a location. @rtype: boolean @note: this can differ for different platforms based on the level of optimization done by their implementation of GLSL (if the attribute is allocated but not used by our shaders). @see: attributeLocation """ loc = glGetAttribLocationARB(self.progObj, name) return (loc != -1) def attributeLocation(self, name): #bruce 090302 renamed from self.attribute() """ Return location of an attribute (per-vertex input) shader variable. If it's not found, return -1 and warn once per session for end users, or raise an AssertionError for developers. @see: _has_shader_attribute """ loc = glGetAttribLocationARB(self.progObj, name) if loc == -1: msg = "Invalid or unused attribute variable name '%s'." % name if EndUser.enableDeveloperFeatures(): # Developers want to know of a mismatch between their Python # and shader programs as soon as possible. Not doing so causes # logic errors, or at least incorrect assumptions, to silently # propagate through the code and makes debugging more difficult. assert 0, msg else: # End users on the other hand, may value program stability more. # Just print a warning if the program is released. Do it only # once per session, since this will be in the inner draw loop! global _warnedVars if name not in _warnedVars: print "Warning:", msg _warnedVars += [name] pass pass pass return loc def setActive(self, on): #bruce 090302 renamed from self.use() """ Activate or deactivate a shader. """ if on: glUseProgramObjectARB(self.progObj) else: glUseProgramObjectARB(0) pass self._active = on return def get_TEXTURE_XFORMS(self): return TEXTURE_XFORMS def get_UNIFORM_XFORMS(self): return UNIFORM_XFORMS def get_N_CONST_XFORMS(self): return N_CONST_XFORMS def supports_transforms(self): #bruce 090309 return SUPPORTS_XFORMS def setupTransforms(self, transforms): # note: this is only called from test_drawing.py (as of before 090302) """ Fill a block of transforms. Depending on the setting of TEXTURE_XFORMS and UNIFORM_XFORMS, the transforms are either in texture memory, or in a uniform array of mat4s ("constant memory"), or unsupported (error if we need any here). @param transforms: A list of transform matrices, where each transform is a flattened list (or Numpy array) of 16 numbers. """ self.n_transforms = nTransforms = len(transforms) if not self.supports_transforms(): assert not nTransforms, "%r doesn't support transforms" % self return self.setActive(True) # Must activate before setting uniforms. assert self._has_uniform("n_transforms") # redundant with following glUniform1iARB(self._uniform("n_transforms"), self.n_transforms) # The shader bypasses transform logic if n_transforms is 0. # (Then location coordinates are in global modeling coordinates.) if nTransforms > 0: if UNIFORM_XFORMS: # Load into constant memory. The GL_EXT_bindable_uniform # extension supports sharing this array of mat4s through a VBO. # XXX Need to bank-switch this data if more than N_CONST_XFORMS. C_transforms = numpy.array(transforms, dtype = numpy.float32) glUniformMatrix4fvARB(self._uniform("transforms"), # Don't over-run the array size. min(len(transforms), N_CONST_XFORMS), GL_TRUE, # Transpose. C_transforms) elif TEXTURE_XFORMS: # Generate a texture ID and bind the texture unit to it. self.transform_memory = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.transform_memory) ## These seem to have no effect with a vertex shader. ## glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) ## glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) # XXX Needed? glEnable(GL_TEXTURE_2D) # Load the transform data into the texture. # # Problem: SIGSEGV kills Python in gleTextureImagePut under # glTexImage2D with more than 250 transforms (16,000 bytes.) # Maybe there's a 16-bit signed size calculation underthere, that's # overflowing the sign bit... Work around by sending transforms to # the texture unit in batches with glTexSubImage2D.) glTexImage2D(GL_TEXTURE_2D, 0, # Level zero - base image, no mipmap. GL_RGBA32F_ARB, # Internal format is floating point. # Column major storage: width = N, height = 4 * RGBA. nTransforms, 4 * 4, 0, # No border. # Data format and type, null pointer to allocate space. GL_RGBA, GL_FLOAT, None) # XXX Split this off into a setTransforms method. batchSize = 250 nBatches = (nTransforms + batchSize-1) / batchSize for i in range(nBatches): xStart = batchSize * i xEnd = min(nTransforms, xStart + batchSize) xSize = xEnd - xStart glTexSubImage2D(GL_TEXTURE_2D, 0, # Subimage x and y offsets and sizes. xStart, 0, xSize, 4 * 4, # List of matrices is flattened into a sequence. GL_RGBA, GL_FLOAT, transforms[xStart:xEnd]) continue # Read back to check proper loading. if CHECK_TEXTURE_XFORM_LOADING: mats = glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT) nMats = len(mats) print "setupTransforms\n[[", for i in range(nMats): nElts = len(mats[i]) perLine = 8 nLines = (nElts + perLine-1) / perLine for line in range(nLines): jStart = perLine * line jEnd = min(nElts, jStart + perLine) for j in range(jStart, jEnd): print "%.2f" % mats[i][j], continue if line < nLines-1: print "\n ", pass if i < nMats-1: print "]\n [", pass continue print "]]" pass else: # should never happen if SUPPORTS_XFORMS is defined correctly assert 0, "can't setupTransforms unless UNIFORM_XFORMS or TEXTURE_XFORMS is set" pass self.setActive(False) # Deactivate again. return pass # End of class GLShaderObject. # == class GLSphereShaderObject(GLShaderObject): """ An analytic sphere shader. This raster-converts analytic spheres, defined by a center point and radius. (Some people call that a ray-tracer, but unlike a real ray-tracer it can't send rays through the scene for reflection/refraction, nor toward the lights to compute shadows.) """ def __init__(self): super(GLSphereShaderObject, self).__init__( "Sphere", sphereVertSrc, sphereFragSrc) return pass # End of class GLSphereShaderObject. class GLCylinderShaderObject(GLShaderObject): """ An analytic cylinder shader. This shader raster-converts analytic tapered cylinders, defined by two end-points determining an axis line-segment, and two radii at the end-points. A constant-radius cylinder is tapered by perspective anyway, so the same shader does cones as well as cylinders. The rendered cylinders are smooth, with no polygon facets. Exact shading, Z depth, and normals are calculated in parallel in the GPU for each pixel. (Some people call that a ray-tracer, but unlike a real ray-tracer it can't send rays through the scene for reflection/refraction, nor toward the lights to compute shadows.) """ _has_uniform_debug_code = True def __init__(self): super(GLCylinderShaderObject, self).__init__( "Cylinder", cylinderVertSrc, cylinderFragSrc) return pass # End of class GLCylinderShaderObject.
NanoCAD-master
cad/src/graphics/drawing/gl_shaders.py
# Copyright 2006-2007 Nanorex, Inc. See LICENSE file for details. """ Fond3D.py - a vector-drawing OpenGL font. The font is a vector-drawing thing. The entries in the font are integer coordinates. The drawing space is 5x7. $Id$ History: wware 060324 - created bruce 071030 - split Font3D out of dimensions module (since used in drawer.py) """ __author__ = "Will" import types import Numeric from Numeric import dot from OpenGL.GL import glVertex from geometry.VQT import cross from graphics.drawing.CS_draw_primitives import drawline # import cycle _font = { ' ': ( ), 'A': (((0, 0), (0, 4), (1, 6), (3, 6), (4, 4), (4, 0)), ((0, 3), (4, 3))), 'B': (((0, 6), (3, 6), (4, 5), (4, 4), (3, 3), (1, 3)), ((3, 3), (4, 2), (4, 1), (3, 0), (0, 0)), ((1, 6), (1, 0))), 'C': ((4, 5), (3, 6), (1, 6), (0, 5), (0, 1), (1, 0), (3, 0), (4, 1)), 'D': (((0, 6), (3, 6), (4, 5), (4, 1), (3, 0), (0, 0)), ((1, 6), (1, 0))), 'E': (((4, 6), (0, 6), (0, 0), (4, 0)), ((0, 3), (3, 3))), 'F': (((4, 6), (0, 6), (0, 0)), ((0, 3), (3, 3))), 'G': ((4, 5), (3, 6), (1, 6), (0, 5), (0, 1), (1, 0), (3, 0), (4, 1), (4, 3), (2, 3)), 'H': (((0, 6), (0, 0)), ((4, 6), (4, 0)), ((0, 3), (4, 3))), 'I': (((1, 6), (3, 6)), ((1, 0), (3, 0)), ((2, 6), (2, 0))), 'J': (((3, 6), (3, 1), (2, 0), (1, 0), (0, 1), (0, 2)), ((2, 6), (4, 6))), 'K': (((0, 0), (0, 6)), ((0, 2), (4, 6)), ((2, 4), (4, 0))), 'L': ((0, 6), (0, 0), (4, 0)), 'M': ((0, 0), (0, 6), (2, 2), (4, 6), (4, 0)), 'N': ((0, 0), (0, 6), (4, 0), (4, 6)), 'O': ((4, 5), (3, 6), (1, 6), (0, 5), (0, 1), (1, 0), (3, 0), (4, 1), (4, 5)), 'P': ((0, 3), (3, 3), (4, 4), (4, 5), (3, 6), (0, 6), (0, 0)), 'Q': (((4, 5), (3, 6), (1, 6), (0, 5), (0, 1), (1, 0), (3, 0), (4, 1), (4, 5)), ((2, 2), (4, 0))), 'R': (((0, 3), (3, 3), (4, 4), (4, 5), (3, 6), (0, 6), (0, 0)), ((2, 3), (4, 0))), 'S': ((4, 5), (3, 6), (1, 6), (0, 5), (0, 4), (1, 3), (3, 3), (4, 2), (4, 1), (3, 0), (1, 0), (0, 1)), 'T': (((0, 6), (4, 6)), ((2, 6), (2, 0))), 'U': ((0, 6), (0, 1), (1, 0), (3, 0), (4, 1), (4, 6)), 'V': ((0, 6), (2, 0), (4, 6)), 'W': ((0, 6), (1, 0), (2, 4), (3, 0), (4, 6)), 'X': (((0, 0), (4, 6)), ((0, 6), (4, 0))), 'Y': (((0, 6), (2, 3), (4, 6)), ((2, 3), (2, 0))), 'Z': ((0, 6), (4, 6), (0, 0), (4, 0)), # do we need lowercase? not yet '.': ((2, 0), (3, 0), (3, 1), (2, 1), (2, 0)), '/': ((0, 0), (3, 6)), '#': (((1, 0), (2, 6)), ((2, 0), (3, 6)), ((0, 4), (4, 4)), ((0, 2), (4, 2))), '+': (((0, 3), (4, 3)), ((2, 5), (2, 1))), '-': ((0, 3), (4, 3)), '*': (((0, 3), (4, 3)), ((1, 1), (3, 5)), ((1, 5), (3, 1))), # Still need: ~ ` ! @ $ % ^ & ( ) _ = [ ] { } ; : ' " | < > , ? '0': (((0, 6), (4, 0)), ((1, 0), (0, 1), (0, 5), (1, 6), (3, 6), (4, 5), (4, 1), (3, 0), (1, 0))), '1': ((1, 0), (3, 0), (2, 0), (2, 6), (1, 5)), '2': ((0, 5), (1, 6), (3, 6), (4, 5), (4, 3), (0, 1), (0, 0), (4, 0)), '3': ((0, 5), (1, 6), (3, 6), (4, 5), (4, 4), (3, 3), (1, 3), (3, 3), (4, 2), (4, 1), (3, 0), (1, 0), (0, 1)), '4': ((1, 6), (0, 3), (4, 3), (4, 6), (4, 0)), '5': ((4, 6), (0, 6), (0, 3), (3, 3), (4, 2), (4, 1), (3, 0), (0, 0)), '6': ((3, 6), (0, 4), (0, 1), (1, 0), (3, 0), (4, 1), (4, 2), (3, 3), (1, 3), (0, 2)), '7': ((0, 6), (4, 6), (2, 0)), '8': ((1, 3), (0, 4), (0, 5), (1, 6), (3, 6), (4, 5), (4, 4), (3, 3), (1, 3), (0, 2), (0, 1), (1, 0), (3, 0), (4, 1), (4, 2), (3, 3)), '9': ((1, 0), (4, 3), (4, 5), (3, 6), (1, 6), (0, 5), (0, 4), (1, 3), (3, 3), (4, 4)), } WIDTH = 5 HEIGHT = 7 SCALE = 0.08 # TODO: WIDTH, HEIGHT should be Font3D attributes; # right now, they are public, used in dimensions.py. # [bruce 071030 comment] class Font3D: def __init__(self, xpos=0, ypos=0, right=None, up=None, rot90=False, glBegin=False): self.glBegin = glBegin if right is not None and up is not None: # The out-of-screen direction for text should always agree with # the "real" out-of-screen direction. self.outOfScreen = cross(right, up) if rot90: self.xflip = xflip = right[1] < 0.0 else: self.xflip = xflip = right[0] < 0.0 xgap = WIDTH halfheight = 0.5 * HEIGHT if xflip: xgap *= -SCALE def fx(x): return SCALE * (WIDTH - 1 - x) else: xgap *= SCALE def fx(x): return SCALE * x if rot90: ypos += xgap xpos -= halfheight * SCALE def tfm(x, y, yoff1, yflip): if yflip: y1 = SCALE * (HEIGHT - 1 - y) else: y1 = SCALE * y return Numeric.array((xpos + yoff1 + y1, ypos + fx(x), 0.0)) else: xpos += xgap ypos -= halfheight * SCALE def tfm(x, y, yoff1, yflip): if yflip: y1 = SCALE * (HEIGHT - 1 - y) else: y1 = SCALE * y return Numeric.array((xpos + fx(x), ypos + yoff1 + y1, 0.0)) self.tfm = tfm def drawString(self, str, yoff=1.0, color=None, tfm=None, _font_X=_font['X']): n = len(str) if not self.glBegin: assert color is not None if hasattr(self, 'tfm'): assert tfm is None if self.xflip: def fi(i): return i - (n + 1) else: def fi(i): return i # figure out what the yflip should be p0 = self.tfm(0, 0, yoff, False) textOutOfScreen = cross(self.tfm(1, 0, yoff, False) - p0, self.tfm(0, 1, yoff, False) - p0) yflip = dot(textOutOfScreen, self.outOfScreen) < 0.0 def tfmgen(i): def tfm2(x, y): return self.tfm(x + (WIDTH+1) * fi(i), y, yoff, yflip) return tfm2 else: assert tfm is not None def tfmgen(i): def tfm2(x, y): return tfm(x + i * (WIDTH+1), y) return tfm2 for i in range(n): # A pen-stroke is a tuple of 2D vectors with integer # coordinates. Each character is represented as a stroke, # or a tuple of strokes e.g. '+' or 'X' or '#'. def drawSequence(seq, tfm=tfmgen(i)): if len(seq) == 0: return # a space character has an empty sequence if type(seq[0][0]) is not types.IntType: # handle multi-stroke characters for x in seq: drawSequence(x) return seq = map(lambda tpl: apply(tfm,tpl), seq) for i in range(len(seq) - 1): pos1, pos2 = seq[i], seq[i+1] if self.glBegin: # This is what we do for grid planes, where "somebody" # is drawGPGrid in drawers.py. # Somebody has already taken care of glBegin(GL_LINES). # TODO: explain this in docstring. glVertex(pos1[0], pos1[1], pos1[2]) glVertex(pos2[0], pos2[1], pos2[2]) # Somebody has already taken care of glEnd(). else: # This is what we do for dimensions. drawline(color, seq[i], seq[i+1]) drawSequence(_font.get(str[i], _font_X)) return pass # end
NanoCAD-master
cad/src/graphics/drawing/Font3D.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ gl_Scale.py - Details of loading the glScale functions. @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: russ 080523: Factored out duplicate code from CS_workers.py and drawers.py . """ try: from OpenGL.GL import glScale except: # The installed version of OpenGL requires argument-typed glScale calls. from OpenGL.GL import glScalef as glScale from OpenGL.GL import glScalef # Note: this is NOT redundant with the above import of glScale -- # without it, displaying an ESP Image gives a NameError traceback # and doesn't work. [Fixed by bruce 070703; bug caught by Eric M using # PyChecker; bug introduced sometime after A9.1 went out.]
NanoCAD-master
cad/src/graphics/drawing/gl_Scale.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ ColorSorter.py - sort primitives and store them in a ColorSortedDisplayList @author: Grantham, Russ @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: This was originally written by Brad Grantham (as part of drawer.py) as a GL optimization to minimize calls on apply_material, by sorting primitives into display lists based on color. Later, it was repurposed by Russ to support runtime-determined drawing styles and to permit some primitives to be drawn using GLSL shaders. For early details see drawer.py history. More recent details are here (though some of them cover the time before drawer.py was split and might be redundant with drawer.py history): 080210 russ Split the single display-list into two second-level lists (with and without color) and a set of per-color sublists so selection and hover-highlight can over-ride Chunk base colors. ColorSortedDisplayList is now a class in the parent's displist attr to keep track of all that stuff. 080311 piotr Added a "drawpolycone_multicolor" function for drawing polycone tubes with per-vertex colors (necessary for DNA display style) 080313 russ Added triangle-strip icosa-sphere constructor, "getSphereTriStrips". 080420 piotr Solved highlighting and selection problems for multi-colored objects (e.g. rainbow colored DNA structures). 080519 russ pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py 081003 russ Added sphere shader-primitive support to CSDLs. 081126 russ Added CSDL shader hover-highlight support, including glname drawing. 090119 russ Added cylinder shader-primitive support. 090220 bruce split class ColorSortedDisplayList into its own file REVIEW [bruce 090114; some of this now belongs in ColorSortedDisplayList.py]: * there are a lot of calls of glGenLists(1) that would be VRAM memory leaks if they didn't deallocate any prior display list being stored in the same attribute as the new one. I *think* they are not leaks, since self._reset is called before them, and it calls self.deallocate_displists, but it would be good to confirm this by independent review, and perhaps to assert that all re-allocated DL id attributes are zero (and zero them in deallocate_displists), to make this very clear. * see my comments dated 090114 about cleaning up .dl, .selected, .selectPick, and activate (and related comments in CrystalShape.py and chunk.py). TODO: Change ColorSorter into a normal class with distinct instances. Give it a stack of instances rather than its current _suspend system. Maybe, refactor some more things between ColorSorter and ColorSortedDisplayList (which also needs renaming). [bruce 090220/090224 comment] """ from OpenGL.GL import GL_BLEND from OpenGL.GL import glBlendFunc from OpenGL.GL import glColor3fv from OpenGL.GL import glDepthMask from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_FALSE from OpenGL.GL import GL_LIGHTING from OpenGL.GL import GL_ONE_MINUS_SRC_ALPHA from OpenGL.GL import glPopName from OpenGL.GL import glPushName from OpenGL.GL import GL_SRC_ALPHA from OpenGL.GL import GL_TRUE from geometry.VQT import A from utilities.debug import print_compact_stack from graphics.drawing.c_renderer import quux_module_import_succeeded if quux_module_import_succeeded: import quux from graphics.drawing.c_renderer import ShapeList_inplace from graphics.drawing.CS_workers import drawcylinder_worker from graphics.drawing.CS_workers import drawline_worker from graphics.drawing.CS_workers import drawpolycone_multicolor_worker from graphics.drawing.CS_workers import drawpolycone_worker from graphics.drawing.CS_workers import drawsphere_worker from graphics.drawing.CS_workers import drawsphere_worker_loop from graphics.drawing.CS_workers import drawsurface_worker from graphics.drawing.CS_workers import drawwiresphere_worker from graphics.drawing.CS_workers import drawtriangle_strip_worker from graphics.drawing.gl_lighting import apply_material # == _DEBUG = False # == import graphics.drawing.drawing_globals as drawing_globals class _fake_GLPane: #bruce 090220 permit_shaders = False # not sure if this matters -- maybe it does for immediate-mode spheres? transforms = () # or make this [] if necessary, but value should never change glprefs = drawing_globals.glprefs #bruce 090304 pass _the_fake_GLPane = _fake_GLPane() # as of 090304 we use this as the non-sorting value of # ColorSorter.glpane, rather than None like before class ColorSorter: """ State Sorter specializing in color (really any object that can be passed to apply_material, which on 20051204 is only color 4-tuples) Invoke start() to begin sorting. Call finish() to complete sorting; pass draw_now = True to also draw all sorted objects at that time. Call schedule() with any function and parameters to be sorted by color. If not sorting, schedule() will invoke the function immediately. If sorting, then the function will not be called until "finish()" or later. In any function which will take part in sorting which previously did not, create a worker function from the old function except the call to apply_material. Then create a wrapper which calls ColorSorter.schedule with the worker function and its params. Also an app can call schedule_sphere and schedule_cylinder to schedule a sphere or a cylinder. Right now this is the only way to directly access the native C++ rendering engine. """ __author__ = "grantham@plunk.org" # For now, these are class globals. As long as OpenGL drawing is # serialized and Sorting isn't nested, this is okay. # # [update, bruce 090220: it's now nested, so this should be changed. # for now, we kluge it with _suspend/_unsuspend_if_needed methods. # Note that this makes ColorSorter.start/finish slower than if we had # a stack of ColorSorter instances, which is what we *should* do.] # # When/if # OpenGL drawing becomes multi-threaded, sorters will have to # become instances. This is probably okay because objects and # materials will probably become objects of their own about that # time so the whole system will get a redesign and # reimplementation. _suspended_states = [] #bruce 090220 def _init_state(): # staticmethod """ Initialize all state variables.except _suspended_states. @note: this is called immediately after defining this class, and in _suspend. """ # Note: all state variables (except _suspended_states) must be # initialized here, saved in _suspend, and restored in # _unsuspend_if_needed. ColorSorter.sorting = False # Guard against nested sorting ColorSorter._sorted = 0 # Number of calls to _add_to_sorter since last _printstats ColorSorter._immediate = 0 # Number of calls to _invoke_immediately since last _printstats ColorSorter._gl_name_stack = [0] # internal record of GL name stack; 0 is a sentinel ColorSorter._parent_csdl = None # Passed from start() to finish() ColorSorter.glpane = _the_fake_GLPane #bruce 090220/090304 ColorSorter._initial_transforms = None #bruce 090220 ColorSorter._permit_shaders = True # modified in ColorSorter.start based on glpane; # note that it has no effect on use of specific shaders # unless a corresponding shader_desired function in ColorSorter.glpane.glprefs # returns true (due to how it's used in this code) # [bruce 090224, revised 090303] # following are guesses by bruce 090220: ColorSorter.sorted_by_color = None ColorSorter._cur_shapelist = None ColorSorter.sphereLevel = -1 return _init_state = staticmethod(_init_state) def _suspend(): # staticmethod """ Save our state so we can reentrantly start. """ # ColorSorter._suspended_states is a list of suspended states. class _attrholder: pass state = _attrholder() if len(ColorSorter._gl_name_stack) > 1: print "fyi: name stack is non-null when suspended -- bug?", ColorSorter._gl_name_stack ##### state.sorting = ColorSorter.sorting state._sorted = ColorSorter._sorted state._immediate = ColorSorter._immediate state._gl_name_stack = ColorSorter._gl_name_stack state._parent_csdl = ColorSorter._parent_csdl state.glpane = ColorSorter.glpane state._initial_transforms = ColorSorter._initial_transforms state._permit_shaders = ColorSorter._permit_shaders state.sorted_by_color = ColorSorter.sorted_by_color state._cur_shapelist = ColorSorter._cur_shapelist state.sphereLevel = ColorSorter.sphereLevel ColorSorter._suspended_states += [state] ColorSorter._init_state() return _suspend = staticmethod(_suspend) def _unsuspend_if_needed(): # staticmethod """ If we're suspended, unsuspend. Otherwise, reinit state as a precaution. """ if ColorSorter._suspended_states: state = ColorSorter._suspended_states.pop() ColorSorter.sorting = state.sorting ColorSorter._sorted = state._sorted ColorSorter._immediate = state._immediate ColorSorter._gl_name_stack = state._gl_name_stack ColorSorter._parent_csdl = state._parent_csdl ColorSorter.glpane = state.glpane ColorSorter._initial_transforms = state._initial_transforms ColorSorter._permit_shaders = state._permit_shaders ColorSorter.sorted_by_color = state.sorted_by_color ColorSorter._cur_shapelist = state._cur_shapelist ColorSorter.sphereLevel = state.sphereLevel pass else: #bruce 090220 guess precaution assert len(ColorSorter._gl_name_stack) == 1, \ "should be length 1: %r" % (ColorSorter._gl_name_stack,) ColorSorter._init_state() return _unsuspend_if_needed = staticmethod(_unsuspend_if_needed) # == def _relative_transforms(): # staticmethod #bruce 090220 """ Return a list or tuple (owned by caller) of the additional transforms we're presently inside, relative to when start() was called. Also do related sanity checks (as assertions). """ t1 = ColorSorter._initial_transforms n1 = len(t1) t2 = ColorSorter.glpane.transforms # should be same or more n2 = len(t2) if n1 < n2: assert t1 == t2[:n1] return tuple(t2[n1:]) else: assert n1 <= n2 return () pass _relative_transforms = staticmethod(_relative_transforms) def _debug_transforms(): # staticmethod #bruce 090220 return [ColorSorter._initial_transforms, ColorSorter._relative_transforms()] _debug_transforms = staticmethod(_debug_transforms) def _transform_point(point): # staticmethod #bruce 090223 """ Apply our current relative transforms to the given point. @return: the transformed point. """ for t in ColorSorter._relative_transforms(): point = t.applyToPoint(point) ### todo (not urgent): implem in TransformControl, # document it there as part of TransformControl_API, # make a class of that name, inherit it from Chunk return point _transform_point = staticmethod(_transform_point) # if necessary, we'll also implement _transform_vector def _warn_transforms_nim(funcname): # staticmethod #bruce 090223 print_compact_stack("bug: use of _relative_transforms nim in %s: " % funcname) return _warn_transforms_nim = staticmethod(_warn_transforms_nim) # == def pushName(glname): """ Record the current pushed GL name, which must not be 0. """ #bruce 060217 Added this assert. assert glname, "glname of 0 is illegal (used as sentinel)" ColorSorter._gl_name_stack.append(glname) pushName = staticmethod(pushName) def popName(): """ Record a pop of the GL name. """ del ColorSorter._gl_name_stack[-1] popName = staticmethod(popName) def _printstats(): """ Internal function for developers to call to print stats on number of sorted and immediately-called objects. """ print ("Since previous 'stats', %d sorted, %d immediate: " % (ColorSorter._sorted, ColorSorter._immediate)) ColorSorter._sorted = 0 ColorSorter._immediate = 0 _printstats = staticmethod(_printstats) def _add_to_sorter(color, func, params): """ Internal function that stores 'scheduled' operations for a later sort, between a start/finish """ ColorSorter._sorted += 1 color = tuple(color) if not ColorSorter.sorted_by_color.has_key(color): ColorSorter.sorted_by_color[color] = [] ColorSorter.sorted_by_color[color].append( (func, params, ColorSorter._gl_name_stack[-1])) _add_to_sorter = staticmethod(_add_to_sorter) def schedule(color, func, params): # staticmethod if ColorSorter.sorting: ColorSorter._add_to_sorter(color, func, params) else: ColorSorter._immediate += 1 # for benchmark/debug stats, mostly # 20060216 We know we can do this here because the stack is # only ever one element deep name = ColorSorter._gl_name_stack[-1] if name: glPushName(name) ## Don't check in immediate drawing, e.g. preDraw_glselect_dict. ## else: ## print "bug_1: attempt to push non-glname", name #Apply appropriate opacity for the object if it is specified #in the 'color' param. (Also do necessary things such as #call glBlendFunc it. -- Ninad 20071009 if len(color) == 4: opacity = color[3] else: opacity = 1.0 if opacity >= 0.0 and opacity != 1.0: glDepthMask(GL_FALSE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) elif opacity == -1: # piotr 080429: I replaced the " < 0" condition with " == -1" # The opacity flag is now used to signal either "unshaded # colors" (opacity == -1) or "multicolor object" (opacity == -2) glDisable(GL_LIGHTING) # Don't forget to re-enable it! glColor3fv(color[:3]) pass apply_material(color) func(params) # Call the draw worker function. if opacity > 0.0 and opacity != 1.0: glDisable(GL_BLEND) glDepthMask(GL_TRUE) elif opacity == -1: # piotr 080429: See my comment above. glEnable(GL_LIGHTING) if name: glPopName() return schedule = staticmethod(schedule) # == def schedule_sphere(color, pos, radius, detailLevel, opacity = 1.0, testloop = 0): """ Schedule a sphere for rendering whenever ColorSorter thinks is appropriate. """ if _DEBUG and ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: print "bare_prim sphere:", ColorSorter._gl_name_stack[-1], \ color, pos, radius, ColorSorter._debug_transforms() if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: # todo: use different flag than .reentrant pos = ColorSorter._transform_point(pos) if ColorSorter.glpane.glprefs.use_c_renderer and ColorSorter.sorting: if len(color) == 3: lcolor = (color[0], color[1], color[2], opacity) else: lcolor = color ColorSorter._cur_shapelist.add_sphere( lcolor, pos, radius, ColorSorter._gl_name_stack[-1]) # 20060208 grantham - I happen to know that one detailLevel # is chosen for all spheres, I just record it over and # over here, and use the last one for the render if (ColorSorter.sphereLevel > -1 and ColorSorter.sphereLevel != detailLevel): raise ValueError, \ "unexpected different sphere LOD levels within same frame" ColorSorter.sphereLevel = detailLevel pass else: # Non-C-coded material rendering (might be sorted and/or use shaders) sphereBatches = ( ColorSorter._permit_shaders and ColorSorter.glpane.glprefs.sphereShader_desired() and drawing_globals.sphereShader_available() ) if len(color) == 3: lcolor = (color[0], color[1], color[2], opacity) else: lcolor = color pass if sphereBatches and ColorSorter._parent_csdl: # Russ 080925: Added. # Collect lists of primitives in the CSDL, rather than sending # them down through the ColorSorter schedule methods into DLs. assert ColorSorter.sorting # since _parent_csdl is present ColorSorter._parent_csdl.addSphere( pos, radius, lcolor, # glnames come from ColorSorter.pushName() ColorSorter._gl_name_stack[-1]) else: vboLevel = ColorSorter.glpane.glprefs.use_drawing_variant # vboLevel sets drawing strategy for unbatched spheres detailLevel = (vboLevel, detailLevel) # KLUGE, explained in a comment inside drawsphere_worker if testloop > 0: worker = drawsphere_worker_loop else: worker = drawsphere_worker ColorSorter.schedule( lcolor, worker, (pos, radius, detailLevel, testloop)) pass return schedule_sphere = staticmethod(schedule_sphere) def schedule_wiresphere(color, pos, radius, detailLevel = 1): """ Schedule a wiresphere for rendering whenever ColorSorter thinks is appropriate. """ if _DEBUG and ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: print "bare_prim wiresphere:", ColorSorter._gl_name_stack[-1], \ color, pos, radius, ColorSorter._debug_transforms() if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: # todo: use different flag than .reentrant pos = ColorSorter._transform_point(pos) ### TODO: for this primitive more than most, it's also necessary to # transform the local coordinate system orientation # used to align the wiresphere. if ColorSorter.glpane.glprefs.use_c_renderer and ColorSorter.sorting: if len(color) == 3: lcolor = (color[0], color[1], color[2], 1.0) else: lcolor = color assert 0, "Need to implement a C add_wiresphere function." ColorSorter._cur_shapelist.add_wiresphere( lcolor, pos, radius, ColorSorter._gl_name_stack[-1]) else: if len(color) == 3: lcolor = (color[0], color[1], color[2], 1.0) else: lcolor = color ColorSorter.schedule(lcolor, drawwiresphere_worker, # Use constant-color line drawing. (color, pos, radius, detailLevel)) schedule_wiresphere = staticmethod(schedule_wiresphere) def schedule_cylinder(color, pos1, pos2, radius, capped = 0, opacity = 1.0): """ Schedule a cylinder for rendering whenever ColorSorter thinks is appropriate. @param pos1: axis endpoint 1 @type pos1: Numeric array (list or tuple won't always work) @param pos2: axis endpoint 2 @type pos2: Numeric array @note: you can pass a tuple of two radii (in place of radius) to make this a tapered cylinder. When cylinder shaders are active and supported, this will use them, otherwise it will use a polycone. """ # check type of radius in the same way for all calls [bruce 090225] if type(radius) == type(()): # radius must be a tuple of 2 radii (length not checked here) ColorSorter._schedule_tapered_cylinder(color, pos1, pos2, radius, capped, opacity) return radius = float(radius) if _DEBUG and ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: print "bare_prim cylinder:", ColorSorter._gl_name_stack[-1], \ color, pos1, pos2, radius, capped, ColorSorter._debug_transforms() if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: # todo: use different flag than .reentrant # note: if drawing a cylinder requires an implicit coordinate system # rather than just the axis endpoints (e.g. if it has a polygonal # cross-section or a surface texture), we'd also need to pick a # disambiguating point on the barrel here, outside this condition, # and include it in what we transform, inside this condition. # This need may be present now if we use this case for non-shader # cylinders (since they have polygonal cross-section). ##### REVIEW pos1 = ColorSorter._transform_point(pos1) pos2 = ColorSorter._transform_point(pos2) if ColorSorter.glpane.glprefs.use_c_renderer and ColorSorter.sorting: if len(color) == 3: lcolor = (color[0], color[1], color[2], 1.0) else: lcolor = color ColorSorter._cur_shapelist.add_cylinder( lcolor, pos1, pos2, radius, ColorSorter._gl_name_stack[-1], capped) else: if len(color) == 3: lcolor = (color[0], color[1], color[2], opacity) else: lcolor = color # Russ 090119: Added. cylinderBatches = ( ColorSorter._permit_shaders and ColorSorter.glpane.glprefs.cylinderShader_desired() and drawing_globals.cylinderShader_available() ) if cylinderBatches and ColorSorter._parent_csdl: # Note: capped is not used; a test indicates it's always on # (at least in the tapered case). [bruce 090225 comment] assert ColorSorter.sorting # since _parent_csdl is present # note: radius can legally be a number, or a tuple of two radii, # but the tuple case never gets this far -- it's diverted above # into _schedule_tapered_cylinder. ColorSorter._parent_csdl.addCylinder( (pos1, pos2), radius, lcolor, # glnames come from ColorSorter.pushName() ColorSorter._gl_name_stack[-1]) else: ColorSorter.schedule(lcolor, drawcylinder_worker, (pos1, pos2, radius, capped)) schedule_cylinder = staticmethod(schedule_cylinder) def _schedule_tapered_cylinder(color, pos1, pos2, radius, capped = 0, opacity = 1.0): """ Schedule a tapered cylinder for rendering whenever ColorSorter thinks is appropriate. @param pos1: axis endpoint 1 @type pos1: Numeric array (list or tuple won't always work) @param pos2: axis endpoint 2 @type pos2: Numeric array @note: When cylinder shaders are active and supported, this will use them, otherwise it will use a polycone. @note: this is for internal use only; it does less checking that it might need to do if there was a public function drawtaperedcylinder that called it. """ #bruce 090225 made this by copying and modifying schedule_cylinder. r1, r2 = map(float, radius) if _DEBUG and ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: print "bare_prim tapered cylinder:", ColorSorter._gl_name_stack[-1], \ color, pos1, pos2, radius, capped, ColorSorter._debug_transforms() if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: # todo: use different flag than .reentrant # (see also comments in schedule_cylinder) pos1 = ColorSorter._transform_point(pos1) pos2 = ColorSorter._transform_point(pos2) if len(color) == 3: lcolor = (color[0], color[1], color[2], opacity) else: lcolor = color use_cylinder_shader = ( ColorSorter._permit_shaders and ColorSorter.glpane.glprefs.coneShader_desired() and drawing_globals.coneShader_available() ) if use_cylinder_shader and ColorSorter._parent_csdl: assert ColorSorter.sorting ColorSorter._parent_csdl.addCylinder( # Note: capped is not used; a test indicates it's always on # (at least in the tapered case). [bruce 090225 comment] (pos1, pos2), radius, lcolor, # glnames come from ColorSorter.pushName() ColorSorter._gl_name_stack[-1]) else: # Note: capped is not used in this case either; a test indicates # it's effectively always on. (If it wasn't, we could try fixing # that by repeating pos1 and pos2 in pos_array, with 0 radius.) # [bruce 090225 comment] vec = pos2 - pos1 pos_array = [pos1 - vec, pos1, pos2, pos2 + vec] rad_array = [r1, r1, r2, r2] ColorSorter.schedule(lcolor, drawpolycone_worker, (pos_array, rad_array)) _schedule_tapered_cylinder = staticmethod(_schedule_tapered_cylinder) def schedule_polycone(color, pos_array, rad_array, capped = 0, opacity = 1.0): """ Schedule a polycone for rendering whenever ColorSorter thinks is appropriate. @note: this never uses shaders, even if it could. For a simple cone or tapered cylinder, you can pass a tuple of 2 radii to drawcylinder which will use shaders when available. """ if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: # todo: use different flag than .reentrant pos_array = [ColorSorter._transform_point(A(pos)) for pos in pos_array] if ColorSorter.glpane.glprefs.use_c_renderer and ColorSorter.sorting and 0: #bruce 090225 'and 0' if len(color) == 3: lcolor = (color[0], color[1], color[2], 1.0) else: lcolor = color assert 0, "Need to implement a C add_polycone_multicolor function." ColorSorter._cur_shapelist.add_polycone( lcolor, pos_array, rad_array, ColorSorter._gl_name_stack[-1], capped) else: if len(color) == 3: lcolor = (color[0], color[1], color[2], opacity) else: lcolor = color ColorSorter.schedule(lcolor, drawpolycone_worker, (pos_array, rad_array)) schedule_polycone = staticmethod(schedule_polycone) def schedule_polycone_multicolor(color, pos_array, color_array, rad_array, capped = 0, opacity = 1.0): """ Schedule a polycone for rendering whenever ColorSorter thinks is appropriate. piotr 080311: this variant accepts a color array as an additional parameter """ if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: # todo: use different flag than .reentrant pos_array = [ColorSorter._transform_point(A(pos)) for pos in pos_array] if ColorSorter.glpane.glprefs.use_c_renderer and ColorSorter.sorting: if len(color) == 3: lcolor = (color[0], color[1], color[2], 1.0) else: lcolor = color assert 0, "Need to implement a C add_polycone function." ColorSorter._cur_shapelist.add_polycone_multicolor( lcolor, pos_array, color_array, rad_array, ColorSorter._gl_name_stack[-1], capped) else: if len(color) == 3: lcolor = (color[0], color[1], color[2], opacity) else: lcolor = color ColorSorter.schedule(lcolor, drawpolycone_multicolor_worker, (pos_array, color_array, rad_array)) schedule_polycone_multicolor = staticmethod(schedule_polycone_multicolor) def schedule_surface(color, pos, radius, tm, nm): """ Schedule a surface for rendering whenever ColorSorter thinks is appropriate. """ if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: # todo: use different flag than .reentrant if ColorSorter._relative_transforms(): ColorSorter._warn_transforms_nim("schedule_surface") if len(color) == 3: lcolor = (color[0], color[1], color[2], 1.0) else: lcolor = color ColorSorter.schedule(lcolor, drawsurface_worker, (pos, radius, tm, nm)) schedule_surface = staticmethod(schedule_surface) def schedule_line(color, endpt1, endpt2, dashEnabled, stipleFactor, width, isSmooth): """ Schedule a line for rendering whenever ColorSorter thinks is appropriate. """ if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: # todo: use different flag than .reentrant endpt1 = ColorSorter._transform_point(endpt1) endpt2 = ColorSorter._transform_point(endpt2) #russ 080306: Signal "unshaded colors" for lines by an opacity of -1. color = tuple(color) + (-1,) ColorSorter.schedule(color, drawline_worker, (endpt1, endpt2, dashEnabled, stipleFactor, width, isSmooth)) schedule_line = staticmethod(schedule_line) def schedule_triangle_strip(color, triangles, normals, colors): """ Schedule a line for rendering whenever ColorSorter thinks is appropriate. """ if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: # todo: use different flag than .reentrant if ColorSorter._relative_transforms(): ColorSorter._warn_transforms_nim("schedule_triangle_strip") ColorSorter.schedule(color, drawtriangle_strip_worker, (triangles, normals, colors)) schedule_triangle_strip = staticmethod(schedule_triangle_strip) # == def start(glpane, csdl, pickstate = None): # staticmethod """ Start sorting - objects provided to "schedule" and primitives such as "schedule_sphere" and "schedule_cylinder" will be stored for a sort at the time "finish" is called. glpane is used for its transform stack. It can be None, but then we will not notice whether primitives we collect are inside any transforms beyond the ones current when we start, and we will also never permit shaders if it's None. csdl is a ColorSortedDisplayList or None, in which case immediate drawing is done. pickstate (optional) indicates whether the parent is currently selected. """ #russ 080225: Moved glNewList here for displist re-org. # (bruce 090114: removed support for use_color_sorted_vbos) #bruce 090220: support _parent_csdl.reentrant #bruce 090220: added new required first argument glpane if ColorSorter._parent_csdl and ColorSorter._parent_csdl.reentrant: assert ColorSorter.sorting ColorSorter._suspend() assert not ColorSorter.sorting, \ "Called ColorSorter.start but already sorting?!" ColorSorter.sorting = True assert ColorSorter._parent_csdl is None #bruce 090105 ColorSorter._parent_csdl = csdl # used by finish() assert ColorSorter.glpane is _the_fake_GLPane if glpane is None: glpane = _the_fake_GLPane assert not glpane.transforms ColorSorter.glpane = glpane ColorSorter._initial_transforms = list(glpane.transforms) ColorSorter._permit_shaders = glpane and glpane.permit_shaders if _DEBUG: print "CS.initial transforms:", ColorSorter._debug_transforms() if csdl is not None: csdl.start(pickstate) #bruce 090224 refactored this into csdl.start if ColorSorter.glpane.glprefs.use_c_renderer: ColorSorter._cur_shapelist = ShapeList_inplace() ColorSorter.sphereLevel = -1 else: ColorSorter.sorted_by_color = {} start = staticmethod(start) # == def finish(draw_now = None): # staticmethod """ Finish sorting -- objects recorded since "start" will be sorted; if draw_now is True, they'll also then be drawn. If there's no parent CSDL, we're in all-in-one-display-list mode, which is still a big speedup over plain immediate-mode drawing. In that case, draw_now must be True since it doesn't make sense to not draw (the drawing has already happened). """ # TODO: refactor by moving some of this into methods in CSDL # (specifically, in ColorSorter._parent_csdl). [bruce 090224 comment] assert ColorSorter.sorting #bruce 090220, appears to be true from this code assert ColorSorter.glpane is not None #bruce 090220 assert ColorSorter.glpane is not _the_fake_GLPane #bruce 090304 if not ColorSorter._parent_csdl: #bruce 090220 revised, check _parent_csdl rather than sorting # (since sorting is always true); looks right but not fully analyzed assert draw_now, "finish(draw_now = False) makes no sense unless ColorSorter._parent_csdl" ### WARNING: DUPLICATE CODE with end of this method # (todo: split out some submethods to clean up) ColorSorter.sorting = False ColorSorter._unsuspend_if_needed() return # Plain immediate-mode, nothing to do. if draw_now is None: draw_now = False # not really needed print_compact_stack( "temporary warning: draw_now was not explicitly passed, using False: ") #### #### before release, leaving it out can mean False without a warning, # since by then it ought to be the "usual case". [bruce 090219] pass from utilities.debug_prefs import debug_pref, Choice_boolean_False debug_which_renderer = debug_pref( "debug print which renderer", Choice_boolean_False) #bruce 060314, imperfect but tolerable parent_csdl = ColorSorter._parent_csdl ColorSorter._parent_csdl = None # this must be done sometime before we return; # it can be done here, since nothing in this method after this # should use it directly or add primitives to it [bruce 090105] if ColorSorter.glpane.glprefs.use_c_renderer: # WARNING: this case has not been maintained for a long time # [bruce 090219 comment] quux.shapeRendererInit() if debug_which_renderer: #bruce 060314 uncommented/revised the next line; it might have # to come after shapeRendererInit (not sure); it definitely has # to come after a graphics context is created and initialized. # 20060314 grantham - yes, has to come after # quux.shapeRendererInit . enabled = quux.shapeRendererGetInteger(quux.IS_VBO_ENABLED) print ("using C renderer: VBO %s enabled" % (('is NOT', 'is')[enabled])) quux.shapeRendererSetUseDynamicLOD(0) if ColorSorter.sphereLevel != -1: quux.shapeRendererSetStaticLODLevels(ColorSorter.sphereLevel, 1) quux.shapeRendererStartDrawing() ColorSorter._cur_shapelist.draw() quux.shapeRendererFinishDrawing() ColorSorter.sorting = False # So chunks can actually record their shapelist # at some point if they want to # ColorSorter._cur_shapelist.petrify() # return ColorSorter._cur_shapelist else: if debug_which_renderer: print "using Python renderer" if parent_csdl is None: # Either all in one display list, or immediate-mode drawing. ### REVIEW [bruce 090114]: are both possibilities still present, # now that several old options have been removed? ColorSorter._draw_sorted( ColorSorter.sorted_by_color) pass else: #russ 080225 parent_csdl.finish( ColorSorter.sorted_by_color) #bruce 090224 refactored this into parent_csdl pass ColorSorter.sorted_by_color = None pass ### WARNING: DUPLICATE CODE with another return statement in this method ColorSorter.sorting = False if draw_now: # Draw the newly-built display list, and any shader primitives as well. if parent_csdl is not None: parent_csdl.draw( # Use either the normal-color display list or the selected one. selected = parent_csdl.selected) ColorSorter._unsuspend_if_needed() return finish = staticmethod(finish) def _draw_sorted(sorted_by_color): #russ 080320: factored out of finish(). """ Traverse color-sorted lists, invoking worker procedures. """ ### REVIEW: still needed? does this have some duplicated code with # parent_csdl.finish? If so, has this been maintained as that's been # modified? [bruce 090224 questions] glEnable(GL_LIGHTING) for color, funcs in sorted_by_color.iteritems(): opacity = color[3] if opacity == -1: #piotr 080429: Opacity == -1 signals the "unshaded color". # Also, see my comment in "schedule". glDisable(GL_LIGHTING) # reenabled below glColor3fv(color[:3]) else: apply_material(color) pass for func, params, name in funcs: if name: glPushName(name) else: pass ## print "bug_4: attempt to push non-glname", name func(params) # Call the draw worker function. if name: glPopName() pass continue if opacity == -1: glEnable(GL_LIGHTING) continue return _draw_sorted = staticmethod(_draw_sorted) pass # end of class ColorSorter ColorSorter._init_state() # (this would be called in __init__ if ColorSorter was a normal class.) # end
NanoCAD-master
cad/src/graphics/drawing/ColorSorter.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version:$Id$ History: 2008-08-14 created. Originally created in BreakOrJoinstrands_GraphicsMode. Moved into its own module as its a general helper function used by many GraphicsModes TODO: - allow prefs_keys as an argument for draw_dnaBaseNumberLabels - refactor. some code (sub def func in draw_dnaBaseNumberLabels) may better be in a dna/model class? """ import foundation.env as env from PyQt4.Qt import QFont, QString from utilities.prefs_constants import dnaBaseNumberLabelColor_prefs_key from utilities.prefs_constants import dnaBaseNumberingOrder_prefs_key from utilities.prefs_constants import dnaBaseNumberLabelChoice_prefs_key def _correct_baseatom_order_for_dnaStrand(strand, baseatoms): """ See a TODO comment in this method body. @see: _draw_dnaBaseNumberLabels() """ #@TODO: REVISE this. Its only called from _draw_dnaBaseNumberLabels() #See if this method should be a moved to DnaStrand class and #some portion of the ._draw_dnaBaseNumberLabels() that returns #baseatoms to class DnaStrandOrSegment. Issue with this refactoring: #there is a method in DnaStrand class that returns baseatoms in bond #direction. May be it needs to be revised/ replaced with #wholechain.get_all_base_atoms_in_order() #-- Ninad 2008-08-06 numberingOrder = env.prefs[dnaBaseNumberingOrder_prefs_key] five_prime_end = strand.get_five_prime_end_base_atom() if five_prime_end: if numberingOrder == 0: if not five_prime_end is baseatoms[0]: baseatoms.reverse() elif numberingOrder == 1: if five_prime_end is baseatoms[0]: baseatoms.reverse() return baseatoms def draw_dnaBaseNumberLabels(glpane): """ Draw the DNA basee number labels. baseNumLabelChoice:(obtained from command class) 0 = None 1 = Strands and Segments 2 = Strands Only 3 = Segments Only @see: _correct_baseatom_order_for_dnaStrand() @see: BuildDna_GraphicsMode._drawLabels() """ win = glpane.win baseNumLabelChoice = env.prefs[dnaBaseNumberLabelChoice_prefs_key] if glpane.scale > 65.0: fontSize = 9 else: fontSize = 12 if baseNumLabelChoice == 0: return segments = win.assy.part.get_topmost_subnodes_of_class(win.assy.DnaSegment) strands = win.assy.part.get_topmost_subnodes_of_class(win.assy.DnaStrand) font = QFont( QString("Helvetica"), fontSize) textColor = env.prefs[dnaBaseNumberLabelColor_prefs_key] # WARNING: Anything smaller than 9 pt on Mac OS X results in # un-rendered text. def func(strandOrSegmentList): for strandOrSegment in strandOrSegmentList: #Don't draw the labels if the strand or segment is hidden if strandOrSegment.all_content_is_hidden(): continue whole_chain = strandOrSegment.get_wholechain() if whole_chain is None: continue baseatoms = whole_chain.get_all_baseatoms_in_order() if isinstance(strandOrSegment, win.assy.DnaStrand): baseatoms = _correct_baseatom_order_for_dnaStrand( strandOrSegment, baseatoms) i = 1 for atm in baseatoms: text = "%d" %(i) highlighting_radius = atm.highlighting_radius() if highlighting_radius < 1.2: highlighting_radius = 4.0 pos = atm.posn() + (0.03+ highlighting_radius)*glpane.out ##+ (glpane.right + glpane.up) glpane.renderTextAtPosition(pos, text, textColor = textColor, textFont = font) i += 1 if baseNumLabelChoice in (1, 2): func(strands) if baseNumLabelChoice in (1, 3): func(segments)
NanoCAD-master
cad/src/graphics/drawing/drawDnaLabels.py
# Copyright 2009 Nanorex, Inc. See LICENSE file for details. """ GLCylinderBuffer.py -- Subclass of GLPrimitiveBuffer for cylinder primitives. @author: Russ @version: $Id$ @copyright: 2009 Nanorex, Inc. See LICENSE file for details. History: Originally written by Russ Fish; designed together with Bruce Smith. Russ 090118: Cloned from GLSphereBuffer.py . ================================================================ See design comments on: * GL contexts, CSDLs and DrawingSet in DrawingSet.py * TransformControl in TransformControl.py * VBOs, IBOs, and GLPrimitiveBuffer in GLPrimitiveBuffer.py * GLPrimitiveSet in GLPrimitiveSet in GLPrimitiveSet.py """ from graphics.drawing.GLPrimitiveBuffer import GLPrimitiveBuffer, HunkBuffer from geometry.VQT import V, A class GLCylinderBuffer(GLPrimitiveBuffer): """ Encapsulate VBO/IBO handles for a batch of cylinders. See doc for common code in the base class, GLPrimitiveBuffer. Draws a bounding-box of quads (or a single billboard quad) to a custom cylinder shader for each cylinder, along with control attribute data. """ def __init__(self, shaderGlobals): """ @param shaderGlobals: the instance of class ShaderGlobals we will be associated with. """ super(GLCylinderBuffer, self).__init__( shaderGlobals ) # Per-vertex attribute hunk VBOs that are specific to the cylinder # shader. Combine endpoints and radii into two vec4's. It would be # nicer to use a twice-4-element mat2x4 attribute VBO, but it would have # to be sent as two attribute slots anyway, because OpenGL only allows # "size" to be 1 to 4 in glVertexAttribPointer. shader = self.shader self.endptRad0Hunks = HunkBuffer(shader, "endpt_rad_0", self.nVertices, 4) self.endptRad1Hunks = HunkBuffer(shader, "endpt_rad_1", self.nVertices, 4) self.hunkBuffers += [self.endptRad0Hunks, self.endptRad1Hunks] return def addCylinders(self, endpts, radii, colors, transform_ids, glnames): """ Cylinder endpts must be a list of tuples of 2 VQT points. Lists or single values may be given for the attributes of the cylinders (radii, colors, transform_ids, and selection glnames). A single value is replicated for the whole batch. The lengths of attribute lists must match the endpoints list. radii and colors are required. Cylinder radii are single numbers (untapered) or tuples of 2 numbers (tapered). Colors are tuples of components: (R, G, B) or (R, G, B, A). transform_ids may be None for endpts in global modeling coordinates. glnames may be None if mouseover drawing will not be done. glnames are 32-bit integers, allocated sequentially and associated with selected objects in a global object dictionary The return value is a list of allocated primitive IDs for the cylinders. """ nCylinders = len(endpts) for endptTuple in endpts: assert type(endptTuple) == type(()) assert len(endptTuple) == 2 if type(radii) == type(()): # A tuple of two numbers. assert len(radii) == 2 radii = (float(radii[0]), float(radii[1])) elif type(radii) != type([]): # Not a list, better be a single number. radii = (float(radii), float(radii)) if type(radii) == type([]): assert len(radii) == nCylinders else: radii = nCylinders * [radii] pass if type(colors) == type([]): assert len(colors) == nCylinders colors = [self.color4(colors) for color in colors] else: colors = nCylinders * [self.color4(colors)] pass if type(transform_ids) == type([]): assert len(transform_ids) == nCylinders else: if transform_ids is None: # This bypasses transform logic in the shader for this cylinder. transform_ids = -1 pass transform_ids = nCylinders * [transform_ids] pass if type(glnames) == type([]): assert len(glnames) == nCylinders else: if glnames is None: glnames = 0 pass glnames = nCylinders * [glnames] pass newIDs = self.newPrimitives(nCylinders) for (newID, endpt2, radius2, color, transform_id, glname) in \ zip(newIDs, endpts, radii, colors, transform_ids, glnames): # Combine each center and radius into one vertex attribute. endptRad0 = V(endpt2[0][0], endpt2[0][1], endpt2[0][2], radius2[0]) endptRad1 = V(endpt2[1][0], endpt2[1][1], endpt2[1][2], radius2[1]) self.endptRad0Hunks.setData(newID, endptRad0) self.endptRad1Hunks.setData(newID, endptRad1) self.colorHunks.setData(newID, color) if self.transform_id_Hunks: self.transform_id_Hunks.setData(newID, transform_id) # Break the glname into RGBA pixel color components, 0.0 to 1.0 . # (Per-vertex attributes are all multiples (1-4) of Float32.) ##rgba = [(glname >> bits & 0xff) / 255.0 for bits in range(24,-1,-8)] ## Temp fix: Ignore the last byte, which always comes back 255 on Windows. rgba = [(glname >> bits & 0xff) / 255.0 for bits in range(16,-1,-8)]+[0.0] self.glname_color_Hunks.setData(newID, rgba) continue return newIDs def grab_untransformed_data(self, primID): #bruce 090223 """ """ endptRad0 = self.endptRad0Hunks.getData(primID) endptRad1 = self.endptRad1Hunks.getData(primID) #### these can be removed after debugging: assert len(endptRad0) == 4, "len(endptRad0) should be 4: %r" % (endptRad0,) assert len(endptRad1) == 4, "len(endptRad1) should be 4: %r" % (endptRad1,) assert len(endptRad0[:3]) == 3, "len slice of 3 (in endptRad0) should be 3: %r" % (endptRad0[:3],) assert len(endptRad1[:3]) == 3, "len slice of 3 (in endptRad1) should be 3: %r" % (endptRad1[:3],) return A(endptRad0[:3]), endptRad0[3], A(endptRad1[:3]), endptRad1[3] def store_transformed_primitive(self, primID, untransformed_data, transform): #bruce 090223 """ @param untransformed_data: something returned earlier from self.grab_untransformed_data(primID) """ # todo: heavily optimize this (see comment in sphere version) point0, radius0, point1, radius1 = untransformed_data point0 = transform.applyToPoint(point0) point1 = transform.applyToPoint(point1) endptRad0 = V(point0[0], point0[1], point0[2], radius0) endptRad1 = V(point1[0], point1[1], point1[2], radius1) self.endptRad0Hunks.setData(primID, endptRad0) self.endptRad1Hunks.setData(primID, endptRad1) return pass # End of class GLCylinderBuffer.
NanoCAD-master
cad/src/graphics/drawing/GLCylinderBuffer.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ Draws the CNT in a ladder display. @author: Ninad, Mark @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ @license: GPL """ import foundation.env as env from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushMatrix from OpenGL.GL import glTranslatef from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.drawers import drawPoint from graphics.drawing.drawers import drawCircle from geometry.VQT import norm, vlen, V, cross from utilities.prefs_constants import DarkBackgroundContrastColor_prefs_key def drawNanotubeLadder(endCenter1, endCenter2, cntRise, glpaneScale, lineOfSightVector, ladderWidth = 6.8, # default diameter for 5x5 CNT beamThickness = 2.0, beam1Color = None, beam2Color = None, stepColor = None ): """ Draws the CNT in a ladder display. @param endCenter1: Nanotube center at end 1 @type endCenter1: B{V} @param endCenter2: Nanotube center at end 2 @type endCenter2: B{V} @param cntRise: Center to center distance between consecutive steps @type cntRise: float @param glpaneScale: GLPane scale used in scaling arrow head drawing @type glpaneScale: float @param lineOfSightVector: Glpane lineOfSight vector, used to compute the the vector along the ladder step. @type: B{V} @param ladderWidth: width of the ladder @type ladderWidth: float @param beamThickness: Thickness of the two ladder beams @type beamThickness: float @param beam1Color: Color of beam1 @param beam2Color: Color of beam2 @see: B{DnaLineMode.Draw } (where it is used) for comments on color convention """ ladderLength = vlen(endCenter1 - endCenter2) # Don't draw the vertical line (step) passing through the startpoint unless # the ladderLength is atleast equal to the cntRise. # i.e. do the drawing only when there are atleast two ladder steps. # This prevents a 'revolving line' effect due to the single ladder step at # the first endpoint if ladderLength < cntRise: return unitVector = norm(endCenter2 - endCenter1) if beam1Color is None: beam1Color = env.prefs[DarkBackgroundContrastColor_prefs_key] if beam2Color is None: beam2Color = env.prefs[DarkBackgroundContrastColor_prefs_key] if stepColor is None: stepColor = env.prefs[DarkBackgroundContrastColor_prefs_key] glDisable(GL_LIGHTING) glPushMatrix() glTranslatef(endCenter1[0], endCenter1[1], endCenter1[2]) pointOnAxis = V(0, 0, 0) vectorAlongLadderStep = cross(-lineOfSightVector, unitVector) unitVectorAlongLadderStep = norm(vectorAlongLadderStep) ladderBeam1Point = pointOnAxis + \ unitVectorAlongLadderStep * 0.5 * ladderWidth ladderBeam2Point = pointOnAxis - \ unitVectorAlongLadderStep * 0.5 * ladderWidth # Following limits the arrowHead Size to the given value. When you zoom out, # the rest of ladder drawing becomes smaller (expected) and the following # check ensures that the arrowheads are drawn proportinately. (Not using a # 'constant' to do this as using glpaneScale gives better results) if glpaneScale > 40: arrowDrawingScale = 40 else: arrowDrawingScale = glpaneScale x = 0.0 while x < ladderLength: drawPoint(stepColor, pointOnAxis) drawCircle(stepColor, pointOnAxis, ladderWidth * 0.5, unitVector) previousPoint = pointOnAxis previousLadderBeam1Point = ladderBeam1Point previousLadderBeam2Point = ladderBeam2Point pointOnAxis = pointOnAxis + unitVector * cntRise x += cntRise ladderBeam1Point = previousPoint + \ unitVectorAlongLadderStep * 0.5 * ladderWidth ladderBeam2Point = previousPoint - \ unitVectorAlongLadderStep * 0.5 * ladderWidth if previousLadderBeam1Point: drawline(beam1Color, previousLadderBeam1Point, ladderBeam1Point, width = beamThickness, isSmooth = True ) drawline(beam2Color, previousLadderBeam2Point, ladderBeam2Point, width = beamThickness, isSmooth = True ) #drawline(stepColor, ladderBeam1Point, ladderBeam2Point) glPopMatrix() glEnable(GL_LIGHTING)
NanoCAD-master
cad/src/graphics/drawing/drawNanotubeLadder.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ sphere_shader.py - Sphere shader GLSL source code. @author: Russ Fish @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. History: Russ 090106: Chopped the GLSL source string blocks out of gl_shaders.py . """ # See the docstring at the beginning of gl_shaders.py for GLSL references. # ================================================================ # == Description: GLSL shader program for sphere primitives, # == including optional halos. # # This raster-converts analytic spheres, defined by a center point and radius. # The rendered spheres are smooth, with no polygon facets. Exact shading, Z # depth, and normals are calculated in parallel in the GPU for each pixel. # # It sends an eye-space ray from the view point to the sphere at each pixel. # Some people call that a ray-tracer, but unlike a real ray-tracer it cannot # send more rays through the scene to intersect other geometry for # reflection/refraction calculations, nor toward the lights for shadows. # # # == How it works: # # A bounding volume of faces may be drawn around the sphere in OpenGL, or # alternately a 'billboard' face may be drawn in front of the the sphere. A # center point and radius are also provided as vertex attributes. The face(s) # must cover at least the pixels where the sphere is to be rendered. Clipping # and lighting settings are also provided to the fragment (pixel) shader. # # The view point, transformed sphere center point and radius, and a ray vector # pointing from the view point to the transformed vertex, are output from the # vertex shader to the fragment shader. This is handled differently for # orthographic and perspective projections, but it is all in pre-projection # gl_ModelViewMatrix 'eye space', with the origin at the eye (camera) location # and XY coordinates parallel to the screen (window) XY. # # When perspective is on, a rotation is done as well, to keep a billboard # drawing pattern oriented directly toward the viewpoint. # # A 'halo' radius is also passed to the fragment shader, for highlighting # selected spheres with a flat disk when the halo drawing-style is selected. # # In between the vertex shader and the fragment shader, the transformed vertex # ray vector coords get interpolated, so it winds up being a transformed ray # from the view point, through the pixel on the bounding volume surface. # # The fragment (pixel) shader is called after raster conversion of primitives, # driven by the fixed-function OpenGL pipeline. The sphere center and radius # are passed from the vertex shader as "varying" quantities. It computes a # normal-sample of an analytic sphere for shading, or discards the pixel if it # is outside the sphere. # # In the fragment shader, the sphere radius-hit comparison is done using the # interpolated points and vectors. That is, if the ray from the eye through the # pixel center passes within the sphere radius of the sphere center point, a # depth and normal on the sphere surface are calculated as a function of the # distance from the center. If the ray is outside the sphere radius, it may # still be within the halo disk radius surrounding the sphere. # <line 0> # ================================================================ # Note: # - if UNIFORM_XFORMS is true in gl_shaders.py, some #defines are # prepended to the following shader sources, by code in gl_shaders.py: # #define UNIFORM_XFORMS (to signal this for use in #ifdefs) # #define N_CONST_XFORMS <array dimension> # - if TEXTURE_XFORMS is true, this one is prepended instead: # #define TEXTURE_XFORMS # - if neither is true, none of those defines are prepended. # The #version statement is prepended before that since it must come first. # [this note and what it's about was revised by bruce 090306] sphereVertSrc = """ // Vertex shader program for sphere primitives. // // See the description at the beginning of this file. // Uniform variables, which are constant inputs for the whole shader execution. uniform int draw_for_mouseover; // 0:use normal color, 1:glname_color. uniform int drawing_style; // 0:normal, 1:override_color, 2:pattern, 3:halo const int DS_NORMAL = 0; const int DS_OVERRIDE_COLOR = 1; const int DS_PATTERN = 2; const int DS_HALO = 3; uniform vec4 override_color; // Color for selection or highlighted drawing. uniform int perspective; // 0:orthographic, 1:perspective. uniform float ndc_halo_width; // Halo width in normalized device coords. uniform int n_transforms; // number of transforms supplied (must be 0 if // they are not supported here) (todo?: to // conserve code and uniforms, we could put this // inside a new ifdef, SUPPORT_TRANSFORMS) #ifdef UNIFORM_XFORMS // Transforms are in uniform (constant) memory. uniform mat4 transforms[N_CONST_XFORMS]; // Must dimension at compile time. #endif #ifdef TEXTURE_XFORMS // Transforms are in texture memory, indexed by a transform slot ID attribute. // Column major, one matrix per column: width=N cols, height=4 rows of vec4s. // GL_TEXTURE_2D is bound to transform matrices, tex coords in (0...1, 0...1). uniform sampler2D transforms; #endif // Attribute variables, which are bound to VBO arrays for each vertex coming in. attribute vec4 center_rad; // Sphere center point and radius. // The following may be set to constants, when no arrays are provided. attribute vec4 color; // Sphere color and opacity (RGBA). attribute float transform_id; // Ignored if -1. (Attribs cannot be ints.) attribute vec4 glname_color; // Mouseover id (glname) as RGBA for drawing. // Varying outputs, interpolated in the pipeline to the fragment (pixel) shader. varying vec3 var_ray_vec; // Vertex dir vec (pixel sample vec in frag shader.) varying vec3 var_center_pt; // Transformed sphere center point. varying vec3 var_view_pt; // Transformed view point. varying float var_radius_sq; // Transformed sphere radius, squared. varying float var_halo_rad_sq; // Halo rad sq at transformed center_pt Z depth. varying vec4 var_basecolor; // Vertex color. void main(void) { // Vertex shader procedure. // Fragment (pixel) color will be interpolated from the vertex colors. if (draw_for_mouseover == 1) var_basecolor = glname_color; else if (drawing_style == DS_OVERRIDE_COLOR) // Solid highlighting or selection. var_basecolor = override_color; else var_basecolor = color; // The center point and radius are combined in one attribute: center_rad. vec4 center = vec4(center_rad.xyz, 1.0); float radius = center_rad.w; // Per-vertex sphere radius. //[ ---------------------------------------------------------------- // Per-primitive transforms. mat4 xform; // always defined; only used when TEXTURE_XFORMS or by debug code if (n_transforms > 0 && int(transform_id) > -1) { // Apply a transform, indexed by a transform slot ID vertex attribute. #ifdef UNIFORM_XFORMS // Get transforms from a fixed-sized block of uniform (constant) memory. // The GL_EXT_bindable_uniform extension allows sharing this through a VBO. center = transforms[int(transform_id)] * center; #endif #ifdef TEXTURE_XFORMS # if 0 // 1 /// Never check in a 1 value. xform = mat4(1.0); /// Testing, override texture xform with identity matrix. # else // Assemble the 4x4 matrix from a column of vec4s stored in texture memory. // Map the 4 rows and N columns onto the (0...1, 0...1) texture coord range. // The first texture coordinate goes across the width of N matrices. float mat = transform_id / float(n_transforms - 1); // (0...N-1)=>(0...1) . // The second tex coord goes down the height of four vec4s for the matrix. xform = mat4(texture2D(transforms, vec2(0.0/3.0, mat)), texture2D(transforms, vec2(1.0/3.0, mat)), texture2D(transforms, vec2(2.0/3.0, mat)), texture2D(transforms, vec2(3.0/3.0, mat))); # endif center = xform * center; #endif // TEXTURE_XFORMS } //] ---------------------------------------------------------------- //[ ================================================================ // Debugging output. #if 0 // 1 /// Never check in a 1 value. // Debugging display: set the colors of a 16x16 sphere array. // test_drawing.py sets the transform_ids. Assume here that // nSpheres = transformChunkLength = 16, so each column is one transform. // The center_rad coord attrib gives the subscripts of the sphere in the array. int offset = int(n_transforms)/2; // Undo the array centering from data setup. int col = int(center_rad.x) + offset; // X picks the columns. int row = int(center_rad.y) + offset; // Y picks the rows. if (col > 10) col--; // Skip the gaps. if (row > 10) row--; # ifdef UNIFORM_XFORMS // Not allowed: mat4 xform = mat4(transforms[int(transform_id)]); xform = mat4(transforms[int(transform_id)][0], transforms[int(transform_id)][1], transforms[int(transform_id)][2], transforms[int(transform_id)][3]); # endif float data; if (true) // false // Display matrix data. // This produces all zeros from a texture-map matrix. // The test identity matrix has 1s in rows 0, 5, 10, and 15, as it should. data = xform[row/4][row - (row/4)*4]; // % is unimplimented. else // Display transform IDs. data = transform_id / float(n_transforms); // Default - Column-major indexing: red is column index, green is row index. var_basecolor = vec4(float(col)/float(n_transforms), float(row)/float(n_transforms), data, 1.0); ///if (data == 0.0) var_basecolor = vec4(1.0); // Zeros in white. if (data > 0.0) var_basecolor = vec4(data, data, data, 1.0); // Fractions in gray. // Matrix labels (1 + xform/100) in blue. if (data > 1.0) var_basecolor = vec4(0.0, 0.0, (data - 1.0) * 8.0, 1.0); #endif //] ================================================================ // Center point in eye space coordinates. vec4 eye_center4 = gl_ModelViewMatrix * center; var_center_pt = eye_center4.xyz / eye_center4.w; // Scaled radius in eye space. (Assume uniform scale on all axes.) vec4 eye_radius4 = gl_ModelViewMatrix * vec4(radius, 0.0, 0.0, 0.0); float eye_radius = length(vec3(eye_radius4)); var_radius_sq = eye_radius * eye_radius; // Square roots are slow. // For halo drawing, scale up drawing primitive vertices to cover the halo. float drawing_radius = eye_radius; // The non-halo radius. if (drawing_style == DS_HALO) { // Take eye-space radius to post-projection units at the center pt depth. // The projection matrix does not change the view alignment, just the scale. vec4 post_proj_radius4 = gl_ProjectionMatrix * vec4(eye_radius, 0.0, var_center_pt.z, 1.0); float post_proj_radius = post_proj_radius4.x / post_proj_radius4.w; // Ratio to increase the eye space radius for the halo. float radius_ratio = (post_proj_radius + ndc_halo_width) / post_proj_radius; // Eye space halo radius for use in the pixel shader. drawing_radius = radius_ratio * eye_radius; var_halo_rad_sq = drawing_radius * drawing_radius; // Square roots are slow. } // The drawing vertices are in unit coordinates, relative to the center point. // Scale by the radius and add to the center point in eye space. vec3 eye_vert_pt; if (perspective == 1) { // When perspective is on, a small rotation is done as well, to keep a // billboard drawing pattern oriented directly toward the viewpoint. vec3 new_z = - normalize(var_center_pt); vec3 new_x = normalize(cross(vec3(0.0, 1.0, 0.0), new_z)); vec3 new_y = cross(new_z, new_x); mat3 rotate = mat3(new_x, new_y, new_z); eye_vert_pt = var_center_pt + drawing_radius * (rotate * gl_Vertex.xyz); // With perspective, look from the origin, toward the vertex (pixel) points. // In eye space, the origin is at the eye point, by definition. var_view_pt = vec3(0.0); var_ray_vec = normalize(eye_vert_pt); } else { eye_vert_pt = var_center_pt + drawing_radius * gl_Vertex.xyz; // Without perspective, look from the 2D pixel position, in the -Z dir. var_view_pt = vec3(eye_vert_pt.xy, 0.0); var_ray_vec = vec3(0.0, 0.0, -1.0); } // Transform the drawing vertex through the projection matrix, making clip // coordinates for the next stage of the pipeline. gl_Position = gl_ProjectionMatrix * vec4(eye_vert_pt, 1.0); } """ # <line 0> # ================================================================ # Note: a prefix with the #version statement is prepended to the following, # together with an optional #define line. sphereFragSrc = """ // Fragment (pixel) shader program for sphere primitives. // // See the description at the beginning of this file. // Uniform variables, which are constant inputs for the whole shader execution. uniform int draw_for_mouseover; // 0: use normal color, 1: glname_color. uniform int drawing_style; // 0:normal, 1:override_color, 2:pattern, 3:halo const int DS_NORMAL = 0; const int DS_OVERRIDE_COLOR = 1; const int DS_PATTERN = 2; const int DS_HALO = 3; uniform vec4 override_color; // Color for selection or highlighted drawing. uniform float override_opacity; // Multiplies the normal color alpha component. // Lighting properties for the material. uniform vec4 material; // Properties: [ambient, diffuse, specular, shininess]. uniform int perspective; uniform vec4 clip; // [near, far, middle, depth_inverse] uniform float DEPTH_TWEAK; // Offset for highlight over-drawing. // A fixed set of lights. uniform vec4 intensity; // Set an intensity component to 0 to ignore a light. uniform vec3 light0; uniform vec3 light1; uniform vec3 light2; uniform vec3 light3; uniform vec3 light0H; // Blinn/Phong halfway/highlight vectors. uniform vec3 light1H; uniform vec3 light2H; uniform vec3 light3H; // Inputs, interpolated by raster conversion from the vertex shader outputs. varying vec3 var_ray_vec; // Pixel sample vec (vertex dir vec in vert shader.) varying vec3 var_center_pt; // Transformed sphere center point. varying vec3 var_view_pt; // Transformed view point. varying float var_radius_sq; // Transformed sphere radius, squared. varying float var_halo_rad_sq; // Halo rad sq at transformed center_pt Z depth. varying vec4 var_basecolor; // Vertex color. void main(void) { // Fragment (pixel) shader procedure. // This is all in *eye space* (pre-projection camera coordinates.) // Vertex ray direction vectors were interpolated into pixel ray vectors. // These go from the view point, through a sample point on the drawn polygon, // *toward* the sphere (but may miss it and be discarded.) vec3 sample_vec = normalize(var_ray_vec); // Interpolation denormalizes vecs. // Project the center point onto the sample ray to find the point where // the sample ray line passes closest to the center of the sphere. // . Vector between the transformed view point and the sphere center. vec3 center_vec = var_center_pt - var_view_pt; // . The distance from the view point to the sphere center plane, which is // perpendicular to the sample_vec and contains the sphere center point. // (The length of the projection of the center_vec onto the sample_vec.) // (Note: The sample_vec is normalized, and the center_vec is not.) float center_plane_dist = dot(center_vec, sample_vec); // . The intersection point of the sample_vec and the sphere center plane is // the point closest to the sphere center point in the sample_vec *and* to // the view point in the sphere center plane. vec3 closest_pt = var_view_pt + center_plane_dist * sample_vec; // How far does the ray pass from the center point in the center plane? // (Compare squares to avoid sqrt, which is slow, as long as we can.) vec3 closest_vec = closest_pt - var_center_pt; float plane_closest_dist_sq = dot(closest_vec, closest_vec); // Compare the ray intersection distance to the sphere and halo disk radii. float intersection_height = 0.0; // Height above the sphere center plane. if (plane_closest_dist_sq > var_radius_sq) { // Outside the sphere radius. Nothing to do if not drawing a halo. if (drawing_style != DS_HALO || plane_closest_dist_sq > var_halo_rad_sq) { discard; // **Exit** } // Hit a halo disk, on the sphere center plane. else { gl_FragColor = override_color; // No shading or lighting on halos. // Not done yet, still have to compute a depth for the halo pixel. } } else { // The ray hit the sphere. Use the Pythagorian Theorem to find the // intersection point between the ray and the sphere, closest to us. // // The closest_pt and the center_pt on the sphere center plane, and the // intersection point between the ray and the sphere, make a right triangle. // The length of the hypotenuse is the distance between the center point and // the intersection point, and is equal to the radius of the sphere. intersection_height = sqrt(var_radius_sq - plane_closest_dist_sq); // Nothing more to do if the intersection point is *behind* the view point // so we are *inside the sphere.* if (intersection_height > center_plane_dist) discard; // **Exit** } // Intersection point of the ray with the sphere, and the sphere normal there. vec3 intersection_pt = closest_pt - intersection_height * sample_vec; vec3 normal = normalize(intersection_pt - var_center_pt); // Distance from the view point to the sphere intersection, transformed into // normalized device coordinates, sets the fragment depth. (Note: The // clipping box depth is passed as its inverse, to save a divide.) float sample_z = intersection_pt.z; if (perspective == 1) { // Perspective: 0.5 + (mid + (far * near / sample_z)) / depth gl_FragDepth = 0.5 + (clip[2] + (clip[1] * clip[0] / sample_z)) * clip[3]; } else { // Ortho: 0.5 + (-middle - sample_z) / depth gl_FragDepth = 0.5 + (-clip[2] - sample_z) * clip[3]; } // Subtract DEPTH_TWEAK to pull Z toward us during highlighted drawing. if (drawing_style != DS_NORMAL) gl_FragDepth -= DEPTH_TWEAK; // No shading or lighting on halos. //// The nVidia 7600GS does not allow return in a conditional. //// if (plane_closest_dist_sq > var_radius_sq) //// return; // **Exit** we are done with a halo pixel. //// Instead of an early return for halo pixels, invert the condition //// and skip the last part of the fragment shader. if (plane_closest_dist_sq <= var_radius_sq) { // Shading control, from the material and lights. float ambient = material[0]; // Accumulate diffuse and specular contributions from the lights. float diffuse = 0.0; diffuse += max(0.0, dot(normal, light0)) * intensity[0]; diffuse += max(0.0, dot(normal, light1)) * intensity[1]; diffuse += max(0.0, dot(normal, light2)) * intensity[2]; diffuse += max(0.0, dot(normal, light3)) * intensity[3]; diffuse *= material[1]; // Diffuse intensity. // Blinn highlight location, halfway between the eye and light vecs. // Phong highlight intensity: Cos^n shinyness profile. (Unphysical.) float specular = 0.0; float shininess = material[3]; specular += pow(max(0.0, dot(normal, light0H)), shininess) * intensity[0]; specular += pow(max(0.0, dot(normal, light1H)), shininess) * intensity[1]; specular += pow(max(0.0, dot(normal, light2H)), shininess) * intensity[2]; specular += pow(max(0.0, dot(normal, light3H)), shininess) * intensity[3]; specular *= material[2]; // Specular intensity. // Do not do lighting while drawing glnames, just pass the values through. if (draw_for_mouseover == 1) gl_FragColor = var_basecolor; else if (drawing_style == DS_OVERRIDE_COLOR) // Highlighting looks 'special' without shinyness. gl_FragColor = vec4(var_basecolor.rgb * vec3(diffuse + ambient), 1.0); else gl_FragColor = vec4(var_basecolor.rgb * vec3(diffuse + ambient) + vec3(specular), // White highlights. var_basecolor.a * override_opacity); } } """
NanoCAD-master
cad/src/graphics/drawing/sphere_shader.py
# Copyright 2009 Nanorex, Inc. See LICENSE file for details. """ cylinder_shader.py - Cylinder shader GLSL source code. @author: Russ Fish @version: $Id$ @copyright: 2009 Nanorex, Inc. See LICENSE file for details. History: Russ 090106: Design description file created. The most detailed level of items will become comments in the GLSL code. """ # See the docstring at the beginning of gl_shaders.py for GLSL references. # ================================================================ # === Description: GLSL shader program for tapered cylinder/cone primitives, # === including endcaps and optional halos. # # This shader raster-converts analytic tapered cylinders, defined by two # end-points determining an axis line-segment, and two radii at the end-points. # A constant-radius cylinder is tapered by perspective anyway, so the same # shader does cones as well as cylinders. # # The rendered cylinders are smooth, with no polygon facets. Exact shading, Z # depth, and normals are calculated in parallel in the GPU for each pixel. # # # === Terminology: # # In the remainder of this description, the word "cylinder" will be used to # refer to the generalized family of tapered cylinders with flat ends # perpendicular to the axis, including parallel cylinders, truncated cones # (frusta), and pointed cones where the radius at one end is zero. (If both # radii are zero, nothing is visible.) # # The two flat circular end surfaces of generalized cylinders are called # "endcaps" here, and the rounded middle part a "barrel". Cylinder barrel # surfaces are ruled surfaces, made up of straight lines that are referred to as # "barrel lines". # # The barrel lines and axis line of a cylinder intersect at a "convergence # point" where the tapered radius goes to zero. This point will be at an # infinite distance for an untapered cylinder, in which case its location is a # pure direction vector, with a W coordinate of zero. Pairs of barrel lines are # coplanar, not skew, because they all intersect at the convergence point. # # # === How the sphere shader works: # # (This is a quick overview, as context for the cylinder shader. See the the # description, comments, and source of the sphere vertex shader program for fine # details of that process that are not repeated here.) # # The vertex shader for spheres doesn't care what OpenGL "unit" drawing pattern # is used to bound the necessary pixels in the window, since spheres are # symmetric in every direction. Unit cubes, tetrahedra, or viewpoint oriented # billboard quads are all treated the same. # # . Their vertices are scaled by the sphere radius and added to the sphere # center point: # drawing_vertex = sphere_center + radius * pattern_vertex # This is done in eye coordinates, where lengths are still valid. # # . When perspective is on, a rotation is done as well, to keep a billboard # drawing pattern oriented directly toward the viewpoint. # # The fragment (pixel) shader for spheres gets a unit ray vector from the # rasterizer, and 3D eye-space data from the vertex shader specifying the # viewpoint and the sphere. The ray gives the direction from the viewpoint # through a pixel in the window in the vicinity of the sphere. # # . For ray-hit detection, it determines whether the closest point to the sphere # center on the ray is within the sphere radius (or surrounding flat halo disk # radius) of the sphere center point. # # . When there is a hit, it calculates the front intersection point of the ray # with the sphere, the 3D normal vector there, the depth of the projection # onto the window pixel, and the shaded pixel color based on the normal, # lights, and material properties. # # # === Cylinder shaders: # # Tapered cylinders/cones are more complicated than spheres, but still have # radial symmetry around the axis to work with. The visible surfaces of a # cylinder are the portion of the barrel surface towards the viewpoint, and at # most one endcap. (*Both* endcaps are hidden by the barrel if the viewpoint is # anywhere between the endcap planes.) # # # === How the cylinder vertex shader works: # # A vertex shader is executed in parallel on each input vertex in the drawing # pattern. Spheres have a single center point and radius, but (tapered) # cylinders have two. All vertices have copies of the associated "attribute" # values, the two axis endpoints and associated end cap radii, packaged into two # 4-vector VBOs for efficiency. # # A particular drawing pattern is assumed as the input to this vertex shader, a # "unit cylinder" quadrilateral billboard with its cylinder axis aligned along # the X axis: four vertices with X in {0.0,1.0}, Y in {+1.0,-1.0}, and Z is 1.0. # # The vertex shader identifies the individual vertices and handles them # individually by knowing where they occur in the input drawing pattern. # # This billboard pattern would emerge unchanged as the output for a unit # cylinder with the viewpoint above the middle of the cylinder, with 1.0 for # both end radii, and endpoints at [0.0,0.0] and [0.0,1.0]. # # In general, the vertices output from the cylinder vertex shader are based on # the input vertices, scaled and positioned by the cylinder axis taper radii and # endpoints. This makes a *symmetric trapezoid billboard quadrilateral*, whose # midline swivels around the cylinder axis to face directly toward the viewpoint # *in eye space coordinates*. The job of this billboard is to cover all of the # visible pixels of the cylinder barrel and endcap. # # [Further details are below, in the vertex shader main procedure.] # # # === A note about pixel (fragment) shaders in general: # # There are a minimum of 32 "interpolators" that smear the "varying" outputs of # the vertex shader over the pixels during raster conversion, and pass them as # inputs to the pixel shaders. Since there are a lot more pixels than vertices, # everything possible is factored out of the pixel shaders as an optimization. # # . Division is an expensive operation, so denominators of fractions are often # passed as inverses for multiplication. # # . Lengths are often passed and compared in squared form (calculated by the # dot-product of a vector with itself) to avoid square roots. # # . Trig functions are expensive, but usually implicit in the results of # dot-products and cross-products, which are cheap GPU operations. # # # === How the cylinder pixel (fragment) shader works: # # Ray-hit detection is in two parts, the endcaps and the barrel surface. # # Endcap circle ray-hit detection is done first, because if the pixel ray hits # the endcap, it won't get through to the barrel. # # Barrel surface ray-hit detection is based on comparing the "passing distance", # between the ray line and the cylinder axis line, with the tapered radius of # the cylinder at the passing point. # # [Further details are below, in the pixel shader main procedure.] # === # <line 0> # ================================================================ # Note: if UNIFORM_XFORMS and/or TEXTURE_XFORMS are set in gl_shaders.py, # some #defines are prepended to the following shader sources, by code in # gl_shaders.py, which include UNIFORM_XFORMS and TEXTURE_XFORMS for ifdefs, # and a number N_CONST_XFORMS. For more details see a similar comment in # sphere_shader.py. [this note and what it's about was revised by bruce 090306] cylinderVertSrc = """ // Vertex shader program for cylinder primitives. // // See the description at the beginning of this file. // XXX Start by copying a lot of stuff from the sphere shaders, factor later. // Debugging aid; fills in *the rest* of the drawing pattern pixels. // (Will not work on nVidia 7000s where return can not be in a conditional.) ///This fails on MBP/8600. Upper-cased, says 'DISCARD' : undeclared identifier. ///#define discard {gl_FragColor = var_basecolor; return;} // Uniform variables, which are constant inputs for the whole shader execution. uniform int draw_for_mouseover; // 0:use normal color, 1:glname_color. uniform int drawing_style; // 0:normal, 1:override_color, 2:pattern, 3:halo const int DS_NORMAL = 0; const int DS_OVERRIDE_COLOR = 1; const int DS_PATTERN = 2; const int DS_HALO = 3; uniform vec4 override_color; // Color for selection or highlighted drawing. uniform int perspective; // 0:orthographic, 1:perspective. uniform float ndc_halo_width; // Halo width in normalized device coords. uniform int n_transforms; #ifdef UNIFORM_XFORMS // Transforms are in uniform (constant) memory. uniform mat4 transforms[N_CONST_XFORMS]; // Must dimension at compile time. #endif #ifdef TEXTURE_XFORMS // Transforms are in texture memory, indexed by a transform slot ID attribute. // Column major, one matrix per column: width=N cols, height=4 rows of vec4s. // GL_TEXTURE_2D is bound to transform matrices, tex coords in (0...1, 0...1). uniform sampler2D transforms; #endif // Attribute variables, which are bound to VBO arrays for each vertex coming in. // Attributes can not be bool or int. // Each non-matrix attribute has space for up to 4 floating-point values. attribute vec4 endpt_rad_0, endpt_rad_1; // Cylinder endpoints and radii, twice. // The following may be set to constants, when no arrays are provided. attribute vec4 color; // Cylinder color and opacity (RGBA). attribute float transform_id; // Ignored if -1. (Attribs cannot be ints.) attribute vec4 glname_color; // Mouseover id (glname) as RGBA for drawing. // Varying outputs, interpolated in the pipeline to the fragment (pixel) shader. // The varying qualifier can be used only with float, floating-point vectors, // matrices, or arrays of these. Structures cannot be varying. // // The nVidia 7000 series (and maybe other older graphics chips), has 32 // interpolators for varyings, but they are organized as 8 vec4s, so we have to // pack some things together. Enumerated as slot-number(n-elements) below. varying vec4 var_pack1; // 1(4), var_ray_vec + var_visible_endcap. vec3 var_ray_vec; // Vertex direction vector (pixel sample vec in frag shader.) int var_visible_endcap; // 0:first endcap visible, 1:second endcap. varying vec4 var_pack2; // 2(4), var_view_pt + var_visibility_type. vec3 var_view_pt; // Transformed view point. int var_visibility_type; // What is visible from the viewpoint. const int VISIBLE_NOTHING = 0; const int VISIBLE_BARREL_ONLY = 1; const int VISIBLE_ENDCAP_ONLY = 2; const int VISIBLE_ENDCAP_AND_BARREL = 3; // Cylinder data. varying vec3 var_endpts[2]; // 3,4(3) Transformed cylinder endpoints. varying vec4 var_pack3; // 5(4) var_radii[2] + var_halo_radii[2]; float var_radii[2]; // Transformed cylinder radii. float var_halo_radii[2]; // Halo radii at transformed endpt Z depth. varying vec4 var_basecolor; // 6(4) Vertex color. // Debugging data. varying vec2 var_input_xy; // 7(2) Drawing pattern billboard vertex. // Vertex shader main procedure. void main(void) { // Fragment (pixel) color will be interpolated from the vertex colors. if (draw_for_mouseover == 1) var_basecolor = glname_color; else if (drawing_style == DS_OVERRIDE_COLOR) // Solid highlighting or selection. var_basecolor = override_color; else var_basecolor = color; #if 0 /// 1 // Debugging vertex shader: identify billboard vertices by color. // X in the billboard drawing pattern is red (0 to 1), Y (+-1) is green. var_basecolor = vec4(gl_Vertex.x, gl_Vertex.y + 1.0 / 2.0, 0.0, 1.0); #endif var_input_xy = gl_Vertex.xy; // The endpoints and radii are combined in one attribute: endpt_rad. vec4 endpts[2]; float radii[2]; int i; endpts[0] = vec4(endpt_rad_0.xyz, 1.0); endpts[1] = vec4(endpt_rad_1.xyz, 1.0); radii[0] = endpt_rad_0.w; // Per-vertex cylinder radii. radii[1] = endpt_rad_1.w; //[ ---------------------------------------------------------------- // Per-primitive transforms. mat4 xform; if (n_transforms > 0 && int(transform_id) > -1) { // Apply a transform, indexed by a transform slot ID vertex attribute. #ifdef UNIFORM_XFORMS // Get transforms from a fixed-sized block of uniform (constant) memory. // The GL_EXT_bindable_uniform extension allows sharing this through a VBO. for (i = 0; i <= 1; i++) endpts[i] = transforms[int(transform_id)] * endpts[i]; #endif #ifdef TEXTURE_XFORMS # if 0 // 1 /// Never check in a 1 value. xform = mat4(1.0); /// Testing, override texture xform with identity matrix. # else // Assemble the 4x4 matrix from a column of vec4s stored in texture memory. // Map the 4 rows and N columns onto the (0...1, 0...1) texture coord range. // The first texture coordinate goes across the width of N matrices. float mat = transform_id / float(n_transforms - 1); // (0...N-1)=>(0...1) . // The second tex coord goes down the height of four vec4s for the matrix. xform = mat4(texture2D(transforms, vec2(0.0/3.0, mat)), texture2D(transforms, vec2(1.0/3.0, mat)), texture2D(transforms, vec2(2.0/3.0, mat)), texture2D(transforms, vec2(3.0/3.0, mat))); # endif for (i = 0; i <= 1; i++) endpts[i] = xform * endpts[i]; #endif // TEXTURE_XFORMS } //] ---------------------------------------------------------------- // Endpoints and radii in eye space coordinates. float billboard_radii[2]; // Either non-haloed, or larger for halos. float max_billboard_radius = 0.0; for (i = 0; i <= 1; i++) { vec4 eye_endpt4 = gl_ModelViewMatrix * endpts[i]; var_endpts[i] = eye_endpt4.xyz / eye_endpt4.w; // Scaled cylinder radii in eye space. (Assume uniform scale on all axes.) vec4 eye_radius4 = gl_ModelViewMatrix * vec4(max(.001, radii[i]), 0.0, 0.0, 0.0); // Russ 090220: zero radius bug. float eye_radius = length(vec3(eye_radius4)); // The non-halo radius. /// GLSL bug? Chained assignment of indexed array elements is broken??? /// var_radii[i] = billboard_radii[i] = eye_radius; var_radii[i] = eye_radius; billboard_radii[i] = eye_radius; // For halo drawing, scale up drawing primitive vertices to cover the halo. if (drawing_style == DS_HALO) { // Take eye-space radius to post-projection units at the endpt depth. // Projection matrix does not change the view alignment, just the scale. vec4 post_proj_radius4 = gl_ProjectionMatrix * vec4(eye_radius, 0.0, var_endpts[i].z, 1.0); float post_proj_radius = post_proj_radius4.x / post_proj_radius4.w; // Ratio to increase the eye space radius for the halo. float radius_ratio = (post_proj_radius + ndc_halo_width)/post_proj_radius; // Eye space halo radius for use in the pixel shader. /// GLSL bug? Chained assignment of indexed array elements is broken??? /// var_halo_radii[i] = billboard_radii[i] = radius_ratio * eye_radius; var_halo_radii[i] = radius_ratio * eye_radius; billboard_radii[i] = var_halo_radii[i]; } max_billboard_radius = max(max_billboard_radius, billboard_radii[i]); } if (perspective == 1) { // In eye space, the origin is at the eye point, by definition. var_view_pt = vec3(0.0); } else { // Without perspective, look from the 2D pixel position, in the -Z dir. var_ray_vec = vec3(0.0, 0.0, -1.0); } //=== Vertex shader details // [See context and general description above, at the beginning of the file.] // // Consider a square truncated pyramid, a tapered box with 6 quadrilateral // faces, tightly surrounding the tapered cylinder. It has 2 square faces // containing circular endcaps, and 4 symmetric trapezoids (tapered rectangles // with 2 parallel edges) tangent to cylinder barrel-lines along their // midlines and connecting the endcap squares. //=== // The cylinder axis and the taper interpolated along it, in eye space units. vec3 axis_line_vec = var_endpts[1] - var_endpts[0]; vec3 axis_line_dir = normalize(axis_line_vec); float axis_length = length(axis_line_vec); float axis_radius_taper = (var_radii[1] - var_radii[0]) / axis_length; //=== // . The shader determines our position vs. the endcap planes by projecting // the viewpoint onto the cylinder axis line, and comparing to the locations // along the axis line of the cylinder endpoints. //=== float vp_axis_proj_len; // Used for perspective only. bool vp_between_endcaps; if (perspective == 1) { // (Note: axis_line_dir vector is normalized, viewpt to endpt vec is not.) vp_axis_proj_len = dot(axis_line_dir, var_view_pt - var_endpts[0]); vp_between_endcaps = vp_axis_proj_len >= 0.0 && // First endpoint. vp_axis_proj_len <= axis_length; // Second endpoint. // (Only valid when NOT between endcap planes, where no endcap is visible.) var_visible_endcap = int(vp_axis_proj_len >= 0.0); } else { // In orthogonal projection, if the axis is very nearly in the XY plane, the // endcaps are nearly edge-on and are ignored. Otherwise, the one with the // greater Z is the visible one. vp_between_endcaps = abs(var_endpts[1].z - var_endpts[0].z) < 0.001; var_visible_endcap = int(var_endpts[1].z > var_endpts[0].z); } //=== // . The viewpoint is inside the barrel surface if the distance to its // projection onto the cylinder axis is less than the cylinder radius, // extrapolated along the axis, at that projection point. //=== bool vp_in_barrel; vec3 endpt_toward_vp_dir[2], endpt_across_vp_dir[2]; if (perspective == 1) { vec3 vp_axis_proj_pt = var_endpts[0] + vp_axis_proj_len * axis_line_dir; float vp_axis_dist = length(vp_axis_proj_pt - var_view_pt); float vp_cyl_radius = vp_axis_proj_len * axis_radius_taper; vp_in_barrel = vp_axis_dist < vp_cyl_radius; // Directions relative to the viewpoint, perpendicular to the cylinder axis // at the endcaps, for constructing swiveling trapezoid billboard vertices. for (i = 0; i <= 1; i++) { if (vp_axis_dist < 0.001) { // Special case when looking straight down the axis. endpt_across_vp_dir[i] = vec3(1.0, 0.0, 0.0); endpt_toward_vp_dir[i] = vec3(0.0, 1.0, 0.0); } else { vec3 vp_endpt_dir = normalize(var_endpts[i] - var_view_pt); // Perpendicular to axis at the endpt, in the axis and viewpt plane. endpt_across_vp_dir[i] = normalize(cross(axis_line_dir, vp_endpt_dir)); // Perpendicular to both the axis and the endpt_across_vp directions. endpt_toward_vp_dir[i] = normalize(cross(axis_line_dir, endpt_across_vp_dir[i])); } } } else { // In orthogonal projection, the barrel surface is hidden from view if the // far endcap is not larger than the near one, and the XY offset of the axis // is not larger than the difference in the endcap radii. #ifdef FULL_SUBSCRIPTING int near_end = var_visible_endcap; int far_end = 1-near_end; float radius_diff = var_radii[near_end] - var_radii[far_end]; float axis_offset = length(var_endpts[near_end].xy-var_endpts[far_end].xy); #else // GLSL bug on GeForce 7600: Expand to use constant subscripts instead. // C6016: Profile requires arrays with non-constant indexes to be uniform float radius_diff; float axis_offset; if (var_visible_endcap == 1) { // near_end == 1, far_end == 0. radius_diff = var_radii[1] - var_radii[0]; axis_offset = length(var_endpts[1].xy-var_endpts[0].xy); } else { // near_end == 0, far_end == 1. radius_diff = var_radii[0] - var_radii[1]; axis_offset = length(var_endpts[0].xy-var_endpts[1].xy); } #endif vp_in_barrel = radius_diff >= 0.0 && axis_offset <= radius_diff; // Directions relative to the view dir, perpendicular to the cylinder axis, // for constructing swiveling trapezoid billboard vertices. if (axis_offset < 0.001) { // Special case looking straight down the axis, close to the -Z direction. endpt_across_vp_dir[0] = endpt_across_vp_dir[1] = vec3(0.0, 1.0, 0.0); endpt_toward_vp_dir[0] = endpt_toward_vp_dir[1] = vec3(1.0, 0.0, 0.0); } else { // Perpendicular to cylinder axis and the view direction, in the XY plane. endpt_across_vp_dir[0] = endpt_across_vp_dir[1] = normalize(cross(axis_line_dir, var_ray_vec)); // Perpendicular to both the cylinder axis and endpt_across_vp directions. endpt_toward_vp_dir[0] = endpt_toward_vp_dir[1] = normalize(cross(axis_line_dir, endpt_across_vp_dir[0])); } } /// vp_in_barrel = vp_between_endcaps = false; /// Single case for debugging. //=== // The output vertices for the billboard quadrilateral are based on the // vertices of the tapered box, with several cases: // // . NE1 does not draw the interior (back sides) of atom and bond surfaces. // When the viewpoint is both (1) between the endcap planes, *and* (2) // inside the barrel surface as well, we draw nothing at all. //=== // Output vertex in eye space for now, will be projected into clipping coords. vec3 billboard_vertex; if (vp_between_endcaps && vp_in_barrel) { var_visibility_type = VISIBLE_NOTHING; billboard_vertex = vec3(0.0, 0.0, -1.0); // Could be anything (nonzero?) } //=== // . When the viewpoint is inside the extension of the barrel surface, only // one endcap is visible, so the output billboard is the square endcap face // whose normal (along the cylinder axis) is toward the viewpoint. //=== else if (vp_in_barrel) { // Just the single visible endcap in this case. var_visibility_type = VISIBLE_ENDCAP_ONLY; #ifdef FULL_SUBSCRIPTING vec3 scaled_across = billboard_radii[var_visible_endcap] * endpt_across_vp_dir[var_visible_endcap]; vec3 scaled_toward = billboard_radii[var_visible_endcap] * endpt_toward_vp_dir[var_visible_endcap]; // The unit rectangle drawing pattern is 0 to 1 in X, elsewhere // corresponding to the direction along the cylinder axis, but here we are // looking only at the endcap square, and so adjust to +-1 in X. billboard_vertex = var_endpts[var_visible_endcap] + (gl_Vertex.x * 2.0 - 1.0) * scaled_across + gl_Vertex.y * scaled_toward; #else // GLSL bug on GeForce 7600: Expand to use constant subscripts instead. // C6016: Profile requires arrays with non-constant indexes to be uniform // The unit rectangle drawing pattern is 0 to 1 in X, elsewhere // corresponding to the direction along the cylinder axis, but here we are // looking only at the endcap square, and so adjust to +-1 in X. if (var_visible_endcap == 1) { vec3 scaled_across = billboard_radii[1] * endpt_across_vp_dir[1]; vec3 scaled_toward = billboard_radii[1] * endpt_toward_vp_dir[1]; billboard_vertex = var_endpts[1] + (gl_Vertex.x * 2.0 - 1.0) * scaled_across + gl_Vertex.y * scaled_toward; } else { vec3 scaled_across = billboard_radii[0] * endpt_across_vp_dir[0]; vec3 scaled_toward = billboard_radii[0] * endpt_toward_vp_dir[0]; billboard_vertex = var_endpts[0] + (gl_Vertex.x * 2.0 - 1.0) * scaled_across + gl_Vertex.y * scaled_toward; } #endif } //=== // . When the viewpoint is between the endcap planes, the output billboard is // only a barrel face trapezoid (made of vertices from the two edges of the // endcap squares that are toward the viewpoint) because the endcaps are // hidden by the barrel. We swivel the pyramid on its axis to align a // barrel face with the viewpoint vector; we only need one barrel face // because it hides all the others. //=== else if (vp_between_endcaps) { var_visibility_type = VISIBLE_BARREL_ONLY; #ifdef FULL_SUBSCRIPTING // Connecting two endcaps, X identifies which one this vertex comes from. int endcap = int(gl_Vertex.x); vec3 scaled_across = billboard_radii[endcap] * endpt_across_vp_dir[endcap]; vec3 scaled_toward = billboard_radii[endcap] * endpt_toward_vp_dir[endcap]; billboard_vertex = var_endpts[endcap] + scaled_toward // Offset to the pyramid face closer to the viewpoint. + gl_Vertex.y * scaled_across; // Offset to either side of the axis. #else // GLSL bug on GeForce 7600: Expand to use constant subscripts instead. // C6016: Profile requires arrays with non-constant indexes to be uniform // Connecting two endcaps, X identifies which one this vertex comes from. if (int(gl_Vertex.x) == 1) { vec3 scaled_across = billboard_radii[1] * endpt_across_vp_dir[1]; vec3 scaled_toward = billboard_radii[1] * endpt_toward_vp_dir[1]; billboard_vertex = var_endpts[1] + scaled_toward // Offset to the pyramid face closer to the viewpoint. + gl_Vertex.y * scaled_across; // Offset to either side of the axis. } else { vec3 scaled_across = billboard_radii[0] * endpt_across_vp_dir[0]; vec3 scaled_toward = billboard_radii[0] * endpt_toward_vp_dir[0]; billboard_vertex = var_endpts[0] + scaled_toward // Offset to the pyramid face closer to the viewpoint. + gl_Vertex.y * scaled_across; // Offset to either side of the axis. } #endif } //=== // . When *both a barrel and an endcap* are visible, an endcap square face and // a barrel face are combined into a single trapezoid by ignoring the shared // edge between them, replacing an 'L' shaped combination with a diagonal // '\'. // // - A subtlety: the max of the two cylinder radii is used for the endcap // square size, because the far end of the cylinder barrel may have a // larger radius than the endcap circle toward us, and we want to cover it // too. (Tighter bounding trapezoids are probably possible, but likely // more work to compute, and would make no difference most of the time // since ray-hit pixel discard is quick.) //=== else { // Connect the outer edge of the visible endcap face with the inner edge of // the hidden endcap face at the other end of the cylinder barrel. var_visibility_type = VISIBLE_ENDCAP_AND_BARREL; int endcap = int(gl_Vertex.x); #ifdef FULL_SUBSCRIPTING vec3 scaled_across = (gl_Vertex.y * max_billboard_radius) * endpt_across_vp_dir[endcap]; vec3 scaled_toward = max_billboard_radius * endpt_toward_vp_dir[endcap]; // On the near face of the pyramid toward the viewpt, for the no-endcap end. vec3 near_edge_midpoint = var_endpts[endcap] + scaled_toward; vec3 near_edge_vertex = near_edge_midpoint + scaled_across; float halo_width = var_halo_radii[endcap]-var_radii[endcap]; #else // GLSL bug on GeForce 7600: Expand to use constant subscripts instead. // C6016: Profile requires arrays with non-constant indexes to be uniform vec3 endcap_across, endcap_toward, endcap_endpt; float halo_width; if (endcap == 1) { endcap_across = endpt_across_vp_dir[1]; endcap_toward = endpt_toward_vp_dir[1]; endcap_endpt = var_endpts[1]; halo_width = var_halo_radii[1]-var_radii[1]; } else { endcap_across = endpt_across_vp_dir[0]; endcap_toward = endpt_toward_vp_dir[0]; endcap_endpt = var_endpts[0]; halo_width = var_halo_radii[0]-var_radii[0]; } vec3 scaled_across = (gl_Vertex.y * max_billboard_radius) * endcap_across; vec3 scaled_toward = max_billboard_radius * endcap_toward; // On the near face of the pyramid toward the viewpt, for the no-endcap end. vec3 near_edge_midpoint = endcap_endpt + scaled_toward; vec3 near_edge_vertex = near_edge_midpoint + scaled_across; #endif if (endcap != var_visible_endcap) { billboard_vertex = near_edge_vertex; if (drawing_style == DS_HALO) { // Halo on the non-endcap cylinder end. // Extend the billboard axis length a little bit for a barrel-end halo. billboard_vertex += axis_line_dir * // Axis direction (unit vector). (float(endcap*2 - 1) // Endcap 0:backward, 1:forward. * halo_width // Eye space halo width. * (axis_length / // Longer when view is more end-on. max(0.1 * axis_length, length(axis_line_vec.xy)))); } } else { // This is a vertex of the visible endcap. Push it away from the viewpt, // across the cylinder endcap by TWICE the radius, to the far face. vec3 away_vec = -(scaled_toward + scaled_toward); if (perspective == 0) { // Orthogonal: parallel projection. billboard_vertex = near_edge_vertex + away_vec; } else { // In perspective, we have to go a little bit wider, projecting the near // endcap-edge vertex width onto the far edge line. Otherwise, slivers // of the edges of the cylinder barrel are sliced away by the billboard // edge. Use the ratio of the distances from the viewpoint to the // midpoints of the far and near edges for widening. This is right when // the endcap is edge-on and face-on, and conservative in between. vec3 far_edge_midpoint = near_edge_midpoint + away_vec; float ratio = length(far_edge_midpoint - var_view_pt) / length(near_edge_midpoint - var_view_pt); billboard_vertex = far_edge_midpoint + ratio * scaled_across; } } } if (perspective == 1) { // With perspective, look from the origin, toward the vertex (pixel) points. var_ray_vec = normalize(billboard_vertex); } else { // Without perspective, look from the 2D pixel position, in the -Z dir. var_view_pt = vec3(billboard_vertex.xy, 0.0); } // Transform the billboard vertex through the projection matrix, making clip // coordinates for the next stage of the pipeline. gl_Position = gl_ProjectionMatrix * vec4(billboard_vertex, 1.0); // Pack some varyings for nVidia 7000 series and similar graphics chips. var_pack1 = vec4(var_ray_vec, float(var_visible_endcap)); var_pack2 = vec4(var_view_pt, float(var_visibility_type)); var_pack3 = vec4(var_radii[0], var_radii[1], var_halo_radii[0], var_halo_radii[1]); } """ # <line 0> # ================================================================ # Note: a prefix with the #version statement is prepended to the following, # together with an optional #define line. cylinderFragSrc = """ // Fragment (pixel) shader program for cylinder primitives. // // See the description at the beginning of this file. // Uniform variables, which are constant inputs for the whole shader execution. uniform int debug_code; // 0:none, 1: show billboard outline. uniform int draw_for_mouseover; // 0: use normal color, 1: glname_color. uniform int drawing_style; // 0:normal, 1:override_color, 2:pattern, 3:halo const int DS_NORMAL = 0; const int DS_OVERRIDE_COLOR = 1; const int DS_PATTERN = 2; const int DS_HALO = 3; uniform vec4 override_color; // Color for selection or highlighted drawing. uniform float override_opacity; // Multiplies the normal color alpha component. // Lighting properties for the material. uniform vec4 material; // Properties: [ambient, diffuse, specular, shininess]. uniform int perspective; uniform vec4 clip; // [near, far, middle, depth_inverse] uniform float DEPTH_TWEAK; // Offset for highlight over-drawing. // A fixed set of lights. uniform vec4 intensity; // Set an intensity component to 0 to ignore a light. uniform vec3 light0; uniform vec3 light1; uniform vec3 light2; uniform vec3 light3; uniform vec3 light0H; // Blinn/Phong halfway/highlight vectors. uniform vec3 light1H; uniform vec3 light2H; uniform vec3 light3H; // Inputs, interpolated by raster conversion from the vertex shader outputs. // The varying qualifier can be used only with float, floating-point vectors, // matrices, or arrays of these. Structures cannot be varying. // // The nVidia 7000 series (and maybe other older graphics chips), has 32 // interpolators for varyings, but they are organized as 8 vec4s, so we have to // pack some things together. Enumerated as slot-number(n-elements) below. varying vec4 var_pack1; // 1(4), var_ray_vec + var_visible_endcap. vec3 var_ray_vec; // Pixel sample vector (vertex dir vec in vert shader.) int var_visible_endcap; // 0:first endcap visible, 1:second endcap. varying vec4 var_pack2; // 2(4), var_view_pt + var_visibility_type. vec3 var_view_pt; // Transformed view point. int var_visibility_type; // What is visible from the viewpoint. const int VISIBLE_NOTHING = 0; const int VISIBLE_BARREL_ONLY = 1; const int VISIBLE_ENDCAP_ONLY = 2; const int VISIBLE_ENDCAP_AND_BARREL = 3; // Cylinder data. varying vec3 var_endpts[2]; // 3,4(3) Transformed cylinder endpoints. varying vec4 var_pack3; // 5(4) var_radii[2] + var_halo_radii[2]; float var_radii[2]; // Transformed cylinder radii. float var_halo_radii[2]; // Halo radii at transformed endpt Z depth. varying vec4 var_basecolor; // 6(4) Vertex color. // Debugging data. varying vec2 var_input_xy; // 7(2) Drawing pattern billboard vertex. // Line functions; assume line direction vectors are normalized (unit vecs.) vec3 pt_proj_onto_line(in vec3 point, in vec3 pt_on_line, in vec3 line_dir) { // Add the projection along the line direction, to a base point on the line. return pt_on_line + dot(line_dir, point - pt_on_line) * line_dir; } float pt_dist_from_line(in vec3 point, in vec3 pt_on_line, in vec3 line_dir) { // (The length of of the cross-product is the sine of the angle between two // vectors, times the lengths of the vectors. Sine is opposite / hypotenuse.) return length(cross(point - pt_on_line, line_dir)); } float pt_dist_sq_from_line(in vec3 point, in vec3 pt_on_line, in vec3 line_dir){ // Avoid a sqrt when we are just going to square the length anyway. vec3 crossprod = cross(point - pt_on_line, line_dir); return dot(crossprod, crossprod); } // Fragment (pixel) shader main procedure. void main(void) { // Unpack varyings that were packed for graphics chips like nVidia 7000s. var_ray_vec = var_pack1.xyz; var_view_pt = var_pack2.xyz; // Varyings are always floats. Because of the interpolation calculations, even // though the same integer value goes into this variable at each vertex, the // interpolated result is not *exactly* the same integer, so round to nearest. var_visible_endcap = int(var_pack1.w + 0.5); var_visibility_type = int(var_pack2.w + 0.5); var_radii[0] = var_pack3.x; var_radii[1] = var_pack3.y; var_halo_radii[0] = var_pack3.z; var_halo_radii[1] = var_pack3.w; #if 0 /// 1 // Debugging vertex shaders: fill in the drawing pattern. gl_FragColor = var_basecolor; // Show the visibility type as a fractional shade in blue. gl_FragColor.b = 0.25 * var_visibility_type; // Sigh. Must not leave uniforms unused. int i = debug_code; float x = override_opacity; vec4 x4 = material; x4 = intensity; x4 = clip; vec3 x3 = light0; x3 = light1; x3 = light2; x3 = light3; x3 = light0H; x3 = light1H; x3 = light2H; x3 = light3H; #else // This is all in *eye space* (pre-projection camera coordinates.) vec3 ray_hit_pt; // For ray-hit and depth calculations. vec3 normal; // For shading calculation. bool debug_hit = false; bool endcap_hit = false; bool halo_hit = false; vec4 halo_color = override_color; // Default from uniform variable. // Debugging - Optionally halo pixels along the billboard outline, along with // the cylinder. Has to be an overlay rather than a background, unless we // abondon use of 'discard' on all of the other hit cases. if (debug_code == 1 && (var_input_xy.x < 0.01 || var_input_xy.x > 0.99 || var_input_xy.y < -0.99 || var_input_xy.y > 0.99)) { // Draw billboard outline pixel like halo, overrides everything else below. debug_hit = true; halo_hit = true; // X in the billboard drawing pattern is red (0 to 1), Y (+-1) is green. halo_color = vec4(var_input_xy.x, var_input_xy.y + 1.0 / 2.0, 0.0, 1.0); } // Nothing to do if the viewpoint is inside the cylinder. if (!debug_hit && var_visibility_type == VISIBLE_NOTHING) discard; // **Exit** // Vertex ray direction vectors were interpolated into pixel ray vectors. // These go from the view point, through a sample point on the drawn polygon, // *toward* the cylinder (but may miss it and be discarded.) vec3 ray_line_dir = normalize(var_ray_vec);// Interpolation denormalizes vecs. // The cylinder axis and taper interpolated along it, in eye space units. // XXX These are known in the vertex shader; consider making them varying. vec3 endpt_0 = var_endpts[0]; vec3 axis_line_vec = var_endpts[1] - endpt_0; vec3 axis_line_dir = normalize(axis_line_vec); float axis_length = length(axis_line_vec); float axis_radius_taper = (var_radii[1] - var_radii[0]) / axis_length; //=== Fragment (pixel) shader details // [See context and general description above, at the beginning of the file.] // // The ray and axis lines in general do not intersect. The closest two // points where a pair of skew lines pass are their intersections with the // line that crosses perpendicular to both of them. The direction vector of // this passing-line is the cross-product of the two line directions. // Project a point on each line onto the passing-line direction with a // dot-product, and take the distance between them with another dot-product. //=== // With normalized inputs, length is sine of the angle between the vectors. vec3 passing_line_crossprod = cross(ray_line_dir, axis_line_dir); vec3 passing_line_dir = normalize(passing_line_crossprod); // The distance between the passing points is the projection of the vector // between two points on the two lines (from cylinder endpoint on the axis // line, to viewpoint on the ray line) onto the passing-line direction vector. float passing_pt_signed_dist = dot(passing_line_dir, var_view_pt - endpt_0); float passing_pt_dist = abs(passing_pt_signed_dist); // The vector between the passing points, from the axis to the ray. vec3 passing_pt_vec = passing_pt_signed_dist * passing_line_dir; // Project the first cylinder endpoint onto the plane containing the ray from // the viewpoint, and perpendicular to the passing_line at the ray_passing_pt. vec3 ep0_proj_pt = endpt_0 + passing_pt_vec; // Project the viewpoint onto a line through the above point, parallel to // the cylinder axis, and going through through the ray_passing_pt we want. vec3 vp_proj_pt = pt_proj_onto_line(var_view_pt, ep0_proj_pt, axis_line_dir); // Distance from the viewpoint to its projection. float vp_proj_dist = length(vp_proj_pt - var_view_pt);// Opposite-side length. // Now we have a right triangle with the right angle where the viewpoint was // projected onto the line, and can compute the ray_passing_pt. // * The hypotenuse is along the ray from the viewpoint to the ray passing // point. // * The sine of the angle at the passing line, between the ray and axis // line directions, is the length of the passing-line cross-product vector. // * The side opposite the passing angle goes from the viewpoint to its // projection. Its length is vp_proj_dist, and tells us the length of the // hypotenuse. Recall that sine is opposite over hypotenuse side lengths: // sine = opp/hyp // opp/sine = opp x 1/sine = opp x hyp/opp = hyp float vp_passing_dist = vp_proj_dist / length(passing_line_crossprod);// Hyp. vec3 ray_passing_pt = var_view_pt + vp_passing_dist * ray_line_dir; // Project back to the plane containing the axis for the other passing point. vec3 axis_passing_pt = ray_passing_pt - passing_pt_vec; //=== // Endcap circle ray-hit detection is done first, because if the pixel ray // hits the endcap, it will not get through to the barrel. //=== // Skip the endcap hit test if no endcap is visible. if (//false && /// May skip the endcap entirely to see just the barrel. !debug_hit && // Skip when already hit debug billboard-outline pixels. var_visibility_type != VISIBLE_BARREL_ONLY) { // (Never VISIBLE_NOTHING.) // (VISIBLE_ENDCAP_ONLY or VISIBLE_ENDCAP_AND_BARREL.) //=== // . The endcap ray-hit test is similar to the sphere shader hit test, in // that a center point and a radius are given, so calculate the distance // that the ray passes from the endcap center point similarly. // // . The difference is that the endcaps are flat circles, not spheres, // projecting to an elliptical shape in general. We deal with that by // intersecting the ray with the endcap plane and comparing the distance // in the plane. (Tweaked for halos as in the sphere shader.) //=== #ifdef FULL_SUBSCRIPTING vec3 endcap_endpt = var_endpts[var_visible_endcap]; float endcap_radius = var_radii[var_visible_endcap]; float endcap_halo_radius = var_halo_radii[var_visible_endcap]; #else // GLSL bug on GeForce 7600: Expand to use constant subscripts instead. // error C6013: Only arrays of texcoords may be indexed in this profile, // and only with a loop index variable vec3 endcap_endpt; float endcap_radius, endcap_halo_radius; if (var_visible_endcap == 1) { endcap_endpt = var_endpts[1]; endcap_radius = var_radii[1]; endcap_halo_radius = var_halo_radii[1]; } else { endcap_endpt = var_endpts[0]; endcap_radius = var_radii[0]; endcap_halo_radius = var_halo_radii[0]; } #endif // Calculate the intersection of the ray with the endcap plane, based on // the projections of the viewpoint and endpoint onto the axis. float vp_dist_along_axis = dot(axis_line_dir, var_view_pt); float ep_dist_along_axis = dot(axis_line_dir, endcap_endpt); float axis_ray_angle_cos = dot(axis_line_dir, ray_line_dir); ray_hit_pt = var_view_pt + ray_line_dir * ((ep_dist_along_axis - vp_dist_along_axis) / axis_ray_angle_cos); // Is the intersection within the endcap radius from the endpoint? vec3 closest_vec = ray_hit_pt - endcap_endpt; float plane_closest_dist = length(closest_vec); if (plane_closest_dist <= endcap_radius) { // Hit the endcap. The normal is the axis direction, pointing outward. endcap_hit = true; normal = axis_line_dir * float(var_visible_endcap * 2 - 1); // * -1 or +1. } else if (drawing_style == DS_HALO && plane_closest_dist <= endcap_halo_radius) { // Missed the endcap, but hit an endcap halo. halo_hit = endcap_hit = true; } else if (var_visibility_type == VISIBLE_ENDCAP_ONLY ) { // Early out. We know only an endcap is visible, and we missed it. discard; // **Exit** } } // Skip the barrel hit test if we already hit an endcap. // (Never VISIBLE_NOTHING here.) if (!endcap_hit && !debug_hit && var_visibility_type != VISIBLE_ENDCAP_ONLY) { // (VISIBLE_BARREL_ONLY, or VISIBLE_ENDCAP_AND_BARREL but missed endcap.) //=== // Barrel surface ray-hit detection is based on comparing the 'passing // distance', between the the ray line and the cylinder axis line, with the // tapered radius of the cylinder at the passing point. // // . Interpolate the tapered radius along the axis line, to the point // closest to the ray on the cylinder axis line, and compare with the // passing distance. //=== float ep0_app_signed_dist = dot(axis_line_dir, axis_passing_pt - endpt_0); float passing_radius = var_radii[0] + axis_radius_taper * ep0_app_signed_dist; if (passing_pt_dist > passing_radius) { // Missed the edge of the barrel, but might still hit a halo on it. float halo_radius_taper = (var_halo_radii[1] - var_halo_radii[0]) / axis_length; float passing_halo_radius = var_halo_radii[0] + halo_radius_taper * ep0_app_signed_dist; halo_hit = drawing_style == DS_HALO && passing_pt_dist <= passing_halo_radius && // Only when between the endcap planes. ep0_app_signed_dist >= 0.0 && ep0_app_signed_dist <= axis_length; if (halo_hit) { // The ray_passing_pt is beyond the edge of the cylinder barrel, but // it is on the passing-line, perpendicular to the ray. Perfect. ray_hit_pt = ray_passing_pt; } else { // Nothing more to do when we miss the barrel of the cylinder entirely. discard; // **Exit** } } if (!halo_hit) { // Barrel/ray intersection. //=== // We already know that the viewpoint is not within the cylinder (the // vertex shader would have set VISIBLE_ENDCAP_ONLY), and that the ray // from the viewpoint to the pixel passes within the cylinder radius of // the axis line, so it has to come in from outside, intersecting the // extended barrel of the cylinder. We will have a hit if the projection // of this intersection point onto the axis line lies between the // endpoints of the cylinder. // // The pixel-ray goes from the viewpoint toward the pixel we are shading, // intersects the cylinder barrel, passes closest to the axis-line inside // the barrel, and intersects the barrel again on the way out. We want // the ray-line vs. barrel-line intersection that is closer to the // viewpoint. (Note: The two intersection points and the ray // passing-point will all be the same point when the ray is tangent to the // cylinder.) // // . First, we find a point on the barrel line that contains the // intersection, in the cross-section plane of the cylinder. This // crossing-plane is perpendicular to the axis line and contains the two // closest passing points, as well as the passing-line through them, // perpendicular to the axis of the cylinder. // // If the radii are the same at both ends of the cylinder, the // barrel-lines are parallel. The projection of the ray-line, along a // ray-plane *parallel to the cylinder axis* into the crossing-plane, is // perpendicular to the passing-line at the ray passing-point, both of // which we already have. //=== // (The 'csp_' prefix is used for objects in the cross-section plane.) vec3 csp_proj_view_pt, csp_passing_pt; float csp_bl_offset_sign, csp_passing_dist_sq, csp_radius_sq; vec3 convergence_pt; // Only used for tapered cylinders. // Untapered cylinders. if (abs(var_radii[1] - var_radii[0]) <= 0.001) { csp_proj_view_pt = var_view_pt + (ray_passing_pt - vp_proj_pt); csp_passing_pt = ray_passing_pt; // With untapered parallel projection, the projected viewpoint is always // on the same side of the axis as the viewpoint. csp_bl_offset_sign = 1.0; csp_passing_dist_sq = passing_pt_dist * passing_pt_dist; csp_radius_sq = var_radii[0] * var_radii[0]; } else { // Tapered cylinders. //=== // If the cylinder radii differ, instead project the viewpoint and the // ray-line direction vector *toward the convergence-point* into the // cross-section plane, scaling by the taper of the cylinder along the // axis. [This is the one place where tapered cylinders and cones are // handled differently from untapered cylinders.] // // - Note: If we project parallel to the axis without tapering toward // the convergence-point, we are working in a plane parallel to the // cylinder axis, which intersects a tapered cylinder or cone in a // hyperbola. Intersecting a ray with a hyperbola is hard. // // Instead, we arrange to work in a ray-plane that includes the // convergence point, as well as the viewpoint and ray direction, so // the intersection of the plane with the cylinder is two straight // lines. It is much easier to intersect a ray with a line. // // - The ray-line and the convergence-point determine a ray-plane, // with the projected ray-line at the intersection of the ray-plane // with the cross-plane. If the ray-line goes through (i.e. within // one pixel of) the convergence-point, we instead discard the // pixel. Right at the tip of a cone, the normal sample is very // unstable, so we can not do valid shading there anyway. //=== // The convergence point is where the radius tapers to zero, along the // axis from the first cylinder endpoint. Notice that if the second // radius is less than the first, the taper is negative, but we want to // go in the positive direction along the axis to the convergence point, // and vice versa. float ep0_cp_axis_signed_dist = var_radii[0] / -axis_radius_taper; convergence_pt = endpt_0 + ep0_cp_axis_signed_dist * axis_line_dir; // XXX Approximation; distance should be in NDC (pixel) coords. float ray_cpt_dist_sq = pt_dist_sq_from_line( // Save a sqrt. convergence_pt, var_view_pt, ray_line_dir); if (ray_cpt_dist_sq <= .00001) discard; // **Exit** //=== // - We calculate a *different 2D ray-line passing-point*, and hence // passing-line, for tapered cylinders and cones. It is the closest // point, on the *projected* ray-line in the cross-plane, to the // cylinder axis passing-point (which does not move.) // // Note: The original passing-point is still *also* on the projected // ray-line, but not midway between the projected barrel-line // intersections anymore. In projecting the ray-line into the // crossing-plane within the ray-plane, the passing-line twists // around the cylinder axis. You can see this from the asymmetry of // the tapering barrel-lines in 3D. The ray-line/barrel-line // intersection further from the convergence-point has to travel // further to the crossing-plane than the nearer one. (Of course, // we do not *know* those points yet, we are in the process of // computing one of them.) //=== // Project the viewpoint into the crossing-plane that contains the // passing-points, along a line to the convergence point, based on the // projection of the viewpoint onto the axis and the positions of the // axis_passing_pt and the convergence point along the axis. We know // above that the viewpoint is not already in the crossing-plane, the // crossing-plane does not go through the convergence point, and the // viewpoint is not on the axis (i.e. inside the cylinder barrel.) float cp_axis_loc = dot(axis_line_dir, convergence_pt); float vp_axis_rel_loc = dot(axis_line_dir, var_view_pt) - cp_axis_loc; float app_axis_rel_loc = dot(axis_line_dir, axis_passing_pt) - cp_axis_loc; // Ratios from similar triangles work with signed distances (relative to // the convergence point along the axis, in this case.) csp_proj_view_pt = convergence_pt + (var_view_pt - convergence_pt) * (app_axis_rel_loc / vp_axis_rel_loc); // New passing point in the cross-section plane. vec3 csp_ray_line_dir = normalize(ray_passing_pt - csp_proj_view_pt); csp_passing_pt = pt_proj_onto_line(axis_passing_pt, csp_proj_view_pt, csp_ray_line_dir); // With tapered projection through the convergence point, when the // convergence point is *between* the cylinder and the projection of the // viewpoint onto the axis line, the projection of the viewpoint // *through* the convergence point into the cross-section plane will be // on the *opposite side* of the axis from the viewpoint. So we need a // sign bit to choose the other barrel-line point in that case. csp_bl_offset_sign = sign(vp_axis_rel_loc) != sign(app_axis_rel_loc) ? -1.0: 1.0; vec3 csp_passing_vec = csp_passing_pt - axis_passing_pt; csp_passing_dist_sq = dot(csp_passing_vec, csp_passing_vec); csp_radius_sq = passing_radius * passing_radius; } // End of tapered cylinders. //=== // [Now we are back to common code for tapered and untapered cylinders.] // // - In the cross-plane, the projected ray-line intersects the circular // cross section of the cylinder at two points, going through the ray // passing-point, and cutting off a chord of the line and an arc of // the circle. Two barrel lines go through the intersection points, // along the surface of the cylinder and also in the ray-plane. Each // of them contains one of the intersection points between the ray and // the cylinder. // // . The chord of the projected ray-line is perpendicularly bisected // by the passing-line, making a right triangle in the cross-plane. // // . The passing-distance is the length of the base of the triangle on // the passing-line, adjacent to the cylinder axis point. // // . The cylinder cross-section circle radius, tapered along the // cylinder to the cross-plane, is the length of the hypotenuse, // between the axis point and the first intersection point of the // ray chord with the circle. // // . The length of the right triangle side opposite the axis, along // the chord of the ray-line toward the viewpoint, is given by the // Pythagorean Theorem. This locates the third vertex of the // triangle, in the cross-plane and the ray-plane. //=== vec3 barrel_line_pt = csp_passing_pt + (sqrt(csp_radius_sq - csp_passing_dist_sq) * csp_bl_offset_sign) * normalize(csp_proj_view_pt - csp_passing_pt); //=== // . The barrel line we want passes through the cross-plane at that // point as well as the convergence-point (which is at infinity in // the direction of the axis for an untapered cylinder.) //=== vec3 barrel_line_dir = axis_line_dir; // Untapered. if (abs(var_radii[1] - var_radii[0]) > 0.001) // Tapered. Sign of line direction does not affect projecting onto it. barrel_line_dir = normalize(convergence_pt - barrel_line_pt); //=== // . Intersect the 3D ray-line with the barrel line in the ray-plane, // giving the 3D ray-cylinder intersection point. Note: this is not in // general contained in the 2D crossing-plane, depending on the location // of the viewpoint. // // - The intersection point may be easily calculated by interpolating // two points on the ray line (e.g. the viewpoint and the ray // passing-point.) The interpolation coefficients are the ratios of // their projection distances to the barrel line. (More // dot-products.) //=== float vp_bl_proj_dist = pt_dist_from_line( var_view_pt, barrel_line_pt, barrel_line_dir); float bl_rpp_proj_dist = pt_dist_from_line( ray_passing_pt, barrel_line_pt, barrel_line_dir); ray_hit_pt = mix(var_view_pt, ray_passing_pt, vp_bl_proj_dist / (vp_bl_proj_dist + bl_rpp_proj_dist)); //=== // . Project the intersection point onto the axis line to determine // whether we hit the cylinder between the endcap planes. If so, // calculate the barrel-line normal. //=== float ip_axis_proj_len = dot(axis_line_dir, ray_hit_pt - endpt_0); if (ip_axis_proj_len < 0.0 || ip_axis_proj_len > axis_length) { // We missed the portion of the cylinder barrel between the endcap // planes. A halo may be required past the end. We find endcap hits // *before* the barrel, so we know there is not one providing a halo on // this end yet. halo_hit = drawing_style == DS_HALO && (ip_axis_proj_len < 0.0 && ip_axis_proj_len >= var_radii[0] - var_halo_radii[0] || ip_axis_proj_len > axis_length && ip_axis_proj_len <= axis_length + var_halo_radii[1] - var_radii[1] ); if (! halo_hit) discard; // **Exit** } else { //=== // - The normal at the intersection point (and all along the same // barrel line) is *perpendicular to the barrel line* (not the // cylinder axis), in the radial plane containing the cylinder axis // and the barrel line. // // - The cross-product of the axis-intersection vector (from the // intersection point toward the axis passing-point), with the // barrel-line direction vector (from the first cylinder endpoint // toward the second) makes a vector tangent to the cross-plane // circle, pointed along the arc toward the passing-line. // // - The cross-product of the tangent-vector, with the barrel-line // direction vector, makes the normal to the cylinder along the // barrel line. //=== vec3 arc_tangent_vec = cross(axis_passing_pt - ray_hit_pt, barrel_line_dir); normal = normalize(cross(arc_tangent_vec, barrel_line_dir)); } // End of barrel normal calculation. } // End of barrel/ray intersection. } // End of barrel hit test. if (debug_hit) { gl_FragDepth = gl_FragCoord.z; // Debug display: Z from billboard polygon. } else { float sample_z = ray_hit_pt.z; // Distance from the view point to the intersection, transformed into // normalized device coordinates, sets the fragment depth. (Note: The // clipping box depth is passed as its inverse, to save a divide.) if (perspective == 1) { // Perspective: 0.5 + (mid + (far * near / sample_z)) / depth gl_FragDepth = 0.5 + (clip[2] + (clip[1] * clip[0] / sample_z)) * clip[3]; } else { // Ortho: 0.5 + (-middle - sample_z) / depth gl_FragDepth = 0.5 + (-clip[2] - sample_z) * clip[3]; } } // Subtract DEPTH_TWEAK to pull Z toward us during highlighted drawing. if (drawing_style != DS_NORMAL) gl_FragDepth -= DEPTH_TWEAK; // Nothing more to do if the intersection point is clipped. if (gl_FragDepth < 0.0 || gl_FragDepth > 1.0) discard; // **Exit** // No shading or lighting on halos. if (halo_hit) { gl_FragColor = halo_color; // No shading or lighting on halos. } else { // Shading control, from the material and lights. float ambient = material[0]; // Accumulate diffuse and specular contributions from the lights. float diffuse = 0.0; diffuse += max(0.0, dot(normal, light0)) * intensity[0]; diffuse += max(0.0, dot(normal, light1)) * intensity[1]; diffuse += max(0.0, dot(normal, light2)) * intensity[2]; diffuse += max(0.0, dot(normal, light3)) * intensity[3]; diffuse *= material[1]; // Diffuse intensity. // Blinn highlight location, halfway between the eye and light vecs. // Phong highlight intensity: Cos^n shinyness profile. (Unphysical.) float specular = 0.0; float shininess = material[3]; specular += pow(max(0.0, dot(normal, light0H)), shininess) * intensity[0]; specular += pow(max(0.0, dot(normal, light1H)), shininess) * intensity[1]; specular += pow(max(0.0, dot(normal, light2H)), shininess) * intensity[2]; specular += pow(max(0.0, dot(normal, light3H)), shininess) * intensity[3]; specular *= material[2]; // Specular intensity. // Do not do lighting while drawing glnames, just pass the values through. if (draw_for_mouseover == 1) gl_FragColor = var_basecolor; else if (drawing_style == DS_OVERRIDE_COLOR) // Highlighting looks 'special' without shinyness. gl_FragColor = vec4(var_basecolor.rgb * vec3(diffuse + ambient), 1.0); else gl_FragColor = vec4(var_basecolor.rgb * vec3(diffuse + ambient) + vec3(specular), // White highlights. var_basecolor.a * override_opacity); } #endif } """
NanoCAD-master
cad/src/graphics/drawing/cylinder_shader.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GLSphereBuffer.py -- Subclass of GLPrimitiveBuffer for sphere primitives. @author: Russ @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originally written by Russ Fish; designed together with Bruce Smith. ================================================================ See design comments on: * GL contexts, CSDLs and DrawingSet in DrawingSet.py * TransformControl in TransformControl.py * VBOs, IBOs, and GLPrimitiveBuffer in GLPrimitiveBuffer.py * GLPrimitiveSet in GLPrimitiveSet in GLPrimitiveSet.py """ from graphics.drawing.GLPrimitiveBuffer import GLPrimitiveBuffer, HunkBuffer from geometry.VQT import V, A class GLSphereBuffer(GLPrimitiveBuffer): """ Encapsulate VBO/IBO handles for a batch of spheres. See doc for common code in the base class, GLPrimitiveBuffer. Draws a bounding-box of quads (or a single billboard quad) to a custom sphere shader for each sphere primitive, along with control attribute data. """ def __init__(self, shaderGlobals): """ @param shaderGlobals: the instance of class ShaderGlobals we will be associated with. """ super(GLSphereBuffer, self).__init__( shaderGlobals ) # Per-vertex attribute hunk VBOs that are specific to the sphere shader. # Combine centers and radii into a 4-element vec4 attribute VBO. (Each # attribute slot takes 4 floats, no matter how many of them are used.) shader = self.shader self.ctrRadHunks = HunkBuffer(shader, "center_rad", self.nVertices, 4) self.hunkBuffers += [self.ctrRadHunks] return def addSpheres(self, centers, radii, colors, transform_ids, glnames): """ Sphere centers must be a list of VQT points. Lists or single values may be given for the attributes of the spheres (radii, colors, transform_ids, and selection glnames). A single value is replicated for the whole batch. The lengths of attribute lists must match the center points list. radii and colors are required. Radii are numbers. Colors are tuples of components: (R, G, B) or (R, G, B, A). transform_ids may be None for centers in global modeling coordinates. glnames may be None if mouseover drawing will not be done. glnames are 32-bit integers, allocated sequentially and associated with selected objects in a global object dictionary The return value is a list of allocated primitive IDs for the spheres. """ nSpheres = len(centers) if type(radii) == type([]): assert len(radii) == nSpheres else: radii = nSpheres * [float(radii)] pass if type(colors) == type([]): assert len(colors) == nSpheres colors = [self.color4(colors) for color in colors] else: colors = nSpheres * [self.color4(colors)] pass if type(transform_ids) == type([]): assert len(transform_ids) == nSpheres else: if transform_ids is None: # This bypasses transform logic in the shader for this sphere. transform_ids = -1 pass transform_ids = nSpheres * [transform_ids] pass if type(glnames) == type([]): assert len(glnames) == nSpheres else: if glnames is None: glnames = 0 pass glnames = nSpheres * [glnames] pass newIDs = self.newPrimitives(nSpheres) for (newID, ctr, radius, color, transform_id, glname) in \ zip(newIDs, centers, radii, colors, transform_ids, glnames): # Combine the center and radius into one vertex attribute. ctrRad = V(ctr[0], ctr[1], ctr[2], radius) self.ctrRadHunks.setData(newID, ctrRad) self.colorHunks.setData(newID, color) if self.transform_id_Hunks: self.transform_id_Hunks.setData(newID, transform_id) # Break the glname into RGBA pixel color components, 0.0 to 1.0 . # (Per-vertex attributes are all multiples (1-4) of Float32.) ##rgba = [(glname >> bits & 0xff) / 255.0 for bits in range(24,-1,-8)] ## Temp fix: Ignore the last byte, which always comes back 255 on Windows. rgba = [(glname >> bits & 0xff) / 255.0 for bits in range(16,-1,-8)]+[0.0] self.glname_color_Hunks.setData(newID, rgba) continue return newIDs def grab_untransformed_data(self, primID): #bruce 090223 """ """ ctrRad = self.ctrRadHunks.getData(primID) return A(ctrRad[:3]), ctrRad[3] def store_transformed_primitive(self, primID, untransformed_data, transform): #bruce 090223 """ @param untransformed_data: something returned earlier from self.grab_untransformed_data(primID) """ # todo: heavily optimize this, by combining multiple values of # untransformed_data into a single array, like Chunk.baseposn # (and/or by coding it in C) point, radius = untransformed_data point = transform.applyToPoint(point) ctrRad = V(point[0], point[1], point[2], radius) self.ctrRadHunks.setData(primID, ctrRad) return pass # End of class GLSphereBuffer.
NanoCAD-master
cad/src/graphics/drawing/GLSphereBuffer.py
""" ### This is a copy of file OpenGL/GL/ARB/vertex_shader.py from ### /Library/Python/2.5/site-packages/PyOpenGL-3.0.0b3-py2.5.egg . ### It replaces the broken version in PyOpenGL-3.0.0a6-py2.5.egg . ### ### The only difference between the two is in the glGetActiveAttribARB function, ### where the max_index and length parameters retrieved from OpenGL by ### glGetObjectParameterivARB are converted to integers. ### ### The only change to the b3 version to make it work in a6 is that the ### glGetObjectParameterivARB function is imported from the b3 ### shader_objects_patch.py file in this same directory. OpenGL extension ARB.vertex_shader $Id$ This module customises the behaviour of the OpenGL.raw.GL.ARB.vertex_shader to provide a more Python-friendly API """ from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from OpenGL.GL import glget import ctypes from OpenGL.raw.GL.ARB.vertex_shader import * from graphics.drawing.shader_objects_patch import glGetObjectParameterivARB ### Added _patch. base_glGetActiveAttribARB = glGetActiveAttribARB def glGetActiveAttribARB(program, index): """ Retrieve the name, size and type of the uniform of the index in the program """ max_index = int(glGetObjectParameterivARB( program, GL_OBJECT_ACTIVE_ATTRIBUTES_ARB )) length = int(glGetObjectParameterivARB( program, GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB)) if index < max_index and index >= 0 and length > 0: name = ctypes.create_string_buffer(length) size = arrays.GLintArray.zeros( (1,)) gl_type = arrays.GLuintArray.zeros( (1,)) base_glGetActiveAttribARB(program, index, length, None, size, gl_type, name) return name.value, size[0], gl_type[0] raise IndexError, 'index out of range from zero to %i' % (max_index - 1, ) glGetActiveAttribARB.wrappedOperation = base_glGetActiveAttribARB
NanoCAD-master
cad/src/graphics/drawing/vertex_shader_patch.py
# Patch to the array size of glBufferDataARB, which should be the size in bytes, # not the array size (number of elements.) glBufferSubDataARB has the same bug. # # From PyOpenGL-3.0.0a6-py2.5.egg/OpenGL/GL/ARB/vertex_buffer_object.py from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from OpenGL.GL import glget import ctypes from OpenGL.raw.GL.ARB.vertex_buffer_object import * def _sizeOfArrayInput( pyArgs, index, wrapper ): return ( # Was arraySize. arrays.ArrayDatatype.arrayByteCount( pyArgs[index] ) ) glBufferDataARB = wrapper.wrapper( glBufferDataARB ).setPyConverter( 'data', arrays.asVoidArray(), ).setPyConverter( 'size' ).setCResolver( 'data', arrays.ArrayDatatype.voidDataPointer , ).setCConverter( 'size', _sizeOfArrayInput, ).setReturnValues( wrapper.returnPyArgument( 'data' ) ) glBufferSubDataARB = wrapper.wrapper( glBufferSubDataARB ).setPyConverter( 'data', arrays.asVoidArray(), ).setPyConverter( 'size' ).setCResolver( 'data', arrays.ArrayDatatype.voidDataPointer , ).setCConverter( 'size', _sizeOfArrayInput, ).setReturnValues( wrapper.returnPyArgument( 'data' ) ) # For VBO drawing, the "indices" argument to glMultiDrawElements is an array of # byte offsets within the bound Index Buffer Object in graphics card RAM, rather # than of an array of pointers to parts of client-side index arrays. See the # docs for glBindBuffer, glDrawElements, and glMultiDrawElements. # # Changed the "indices" argument type from ctypes.POINTER(ctypes.c_void_p) to # arrays.GLintArray, like the "first" argument of glMultiDrawArrays. glMultiDrawElementsVBO = platform.createExtensionFunction( 'glMultiDrawElementsEXT', dll=platform.GL, resultType=None, argTypes=(constants.GLenum, arrays.GLsizeiArray, constants.GLenum, arrays.GLintArray, constants.GLsizei,), doc = ('glMultiDrawElementsEXT( GLenum(mode), GLsizeiArray(count), ' 'GLenum(type), GLintArray(indices), GLsizei(primcount) ) -> None'), argNames = ('mode', 'count', 'type', 'indices', 'primcount',), )
NanoCAD-master
cad/src/graphics/drawing/vbo_patch.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ TransformControl.py -- A local coordinate frame for a set of CSDLs. WARNING: This class is deprecated, though it's still used by some test cases and still partly supported in the code. It was never finished. As of 090223, the CSDL attribute intended for instances of this class is filled by Chunks. @author: Russ @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originally written by Russ Fish; designed together with Bruce Smith. ================================================================ See design comments on: * GL contexts, CSDLs and DrawingSet in DrawingSet.py * TransformControl in TransformControl.py * VBOs, IBOs, and GLPrimitiveBuffer in GLPrimitiveBuffer.py * GLPrimitiveSet in GLPrimitiveSet in GLPrimitiveSet.py == TransformControl == * CSDLs are now created with a TransformControl reference as an argument (and are internally listed in it while they exist). - This TransformControl reference is constant (although the transform in the TransformControl is mutable.) - For convenience, the TransformControl argument can be left out if you don't want to use a TransformControl to move the CSDL. This has the same effect as giving a TransformControl whose transform remains as the identity matrix. * A TransformControl controls where a set of CSDLs appear, with a common coordinate transform giving the local coordinate system for the objects in the CSDLs. * A TransformControl gains and loses CSDLs, as they are created in it, or destroyed. * The API need not provide external access to, or direct modification of, the set of CSDLs in a TransformControl. * The transform is mutable, represented by a quaternion and a translation vector (or the equivalent). (Later, we may have occasion to add a scale as well.) * Interactions like dragging can be efficiently done by drawing the drag selection as a separate DrawingSet, viewed through an incremental modeling transform controlled by mouse drag motion. Afterward, the drag transform will be combined with the transform in the TransformControls for the selected CSDLs (using changeAllTransforms, below). * Since there is no matrix stack to change in the middle of a batched draw, TransformControl transforms are stored in the graphics card RAM for use by vertex shaders, either in texture memory or constant memory, indexed by a transform_id. Transform_ids are stored in per-vertex attribute VBOs. ** If this proves too slow or unworkable on some drivers which could otherwise be supported, there is a fallback option of modifying VBO vertex coordinates after transforms change (lazily, as needed for drawing). * The parameters for primitives are stored in per-vertex attribute VBOs as well, in local coordinates relative to the TransformControl transform. * DrawingSet.changeAllTransforms(transform) combines a given transform with those stored in the TransformControls of all CSDLs in this DrawingSet. (Note that this affects all CSDLs in those TransformControls, even if they are not in this DrawingSet.) """ import graphics.drawing.drawing_constants as drawing_constants from geometry.VQT import Q import Numeric import math from OpenGL.GL import glTranslatef, glRotatef def floatIdent(size): return Numeric.asarray(Numeric.identity(size), Numeric.Float) def qmat4x4(quat): """ Convert the 3x3 matrix from a quaternion into a 4x4 matrix. """ mat = floatIdent(4) mat[0:3, 0:3] = quat.matrix return mat _transform_id_counter = -1 class TransformControl: """ @warning: this is a deprecated class; see module docstring for more info. Store a shared mutable transform value for a set of CSDLs sharing a common local coordinate frame, and help the graphics subsystem render those CSDLs using that transform value. (This requires also storing that set of CSDLs.) The 4x4 transform matrix we store starts out as the identity, and can be modified using the rotate() and translate() methods, or reset using the setRotateTranslate() method. If you want self's transform expressed as the composition of a rotation quaternion and translation vector, use the getRotateTranslate method. """ # REVIEW: document self.transform and self.transform_id as public attributes? # Any others? TODO: Whichever are not public, rename as private. # Implementation note: # Internally, we leave the transform in matrix form since that's what we'll # need for drawing primitives in shaders. # (No quaternion or even rotation matrix functions are built in over there.) def __init__(self): # A unique integer ID for each TransformControl. global _transform_id_counter _transform_id_counter += 1 self.transform_id = _transform_id_counter # Support for lazily updating drawing caches, namely a # timestamp showing when this transform matrix was last changed. ### REVIEW: I think we only need a valid flag, not any timestamps -- # at least for internal use. If we have clients but not subscribers, # then they could make use of our changed timestamp. [bruce 090203] self.changed = drawing_constants.eventStamp() self.cached = drawing_constants.NO_EVENT_YET self.transform = floatIdent(4) return # == def rotate(self, quat): """ Post-multiply self's transform with a rotation given by a quaternion. """ self.transform = Numeric.matrixmultiply(self.transform, qmat4x4(quat)) self.changed = drawing_constants.eventStamp() return def translate(self, vec): """ Post-multiply the transform with a translation given by a 3-vector. """ # This only affects the fourth row x,y,z elements. self.transform[3, 0:3] += vec self.changed = drawing_constants.eventStamp() return def setRotateTranslate(self, quat, vec): """ Replace self's transform with the composition of a rotation quat (done first) and a translation vec (done second). """ ## self.transform = floatIdent(4) ## self.rotate(quat) # optimize that: self.transform = qmat4x4(quat) self.translate(vec) # this also sets self.changed return def getRotateTranslate(self): """ @return: self's transform value, as the tuple (quat, vec), representing the translation 3-vector vec composed with the rotation quaternion quat (rotation to be done first). @rtype: (quat, vec) where quat is of class Q, and vec is a length-3 sequence of undocumented type. If self is being used to transform a 3d model, the rotation should be applied to the model first, to orient it around its presumed center; then the translation, to position the rotated model with its center in the desired location. This means that the opposite order should be used to apply them to the GL matrices (which give the coordinate system for drawing), i.e. first glTranslatef, then glRotatef. """ # With no scales, skews, or perspective the right column is [0, 0, 0, # 1]. The upper right 3x3 is a rotation matrix giving the orientation #### ^^^^^ #### REVIEW: should this 'right' be 'left'? #### [bruce 090203 comment] # of the new right-handed orthonormal local coordinate frame, and the # left-bottom-row 3-vector is the translation that positions the origin # of that frame. quat = Q(self.transform[0, 0:3], self.transform[1, 0:3], self.transform[2, 0:3]) vec = self.transform[3, 0:3] return (quat, vec) def applyTransform(self): """ Apply self's transform to the GL matrix stack. (Pushing/popping the stack, if needed, is the caller's responsibility.) @note: this is used for display list primitives in CSDLs, but not for shader primitives in CSDLs. """ (q, v) = self.getRotateTranslate() glTranslatef(v[0], v[1], v[2]) glRotatef(q.angle * 180.0 / math.pi, q.x, q.y, q.z) return pass # end of class TransformControl # end
NanoCAD-master
cad/src/graphics/drawing/TransformControl.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ GLPrimitiveSet.py -- Cached data structure for rapidly drawing a set of batched primitives collected from the CSDLs in a DrawingSet, along with any other kind of drawable content in the CSDLs. @author: Russ @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Originally written by Russ Fish; designed together with Bruce Smith. ================================================================ See design comments on: * GL contexts, CSDLs and DrawingSet in DrawingSet.py * TransformControl in TransformControl.py * VBOs, IBOs, and GLPrimitiveBuffer in GLPrimitiveBuffer.py * GLPrimitiveSet in GLPrimitiveSet in GLPrimitiveSet.py == GLPrimitiveSet == * GLPrimitiveSets are used for drawing sets of primitives from the VBO array hunks, using indexed glMultiDrawElements calls. They are created and cached by DrawingSet.draw() from the possibly-large sequences of primitive types and IDs contained in the CSDLs in the DrawingSet. * Each GLPrimitiveSet caches a drawIndex for glMultiDrawElements, which gives the locations and lengths of blocks of indices in a hunk IBO to draw. * It is generated from the primitive IDs contained in the CSDL's of a DrawingSet, and stored as two host-side C/Numpy arrays for the locations and lengths. * Possible optimization: The drawing index could use a separate run of vertices for each primitive, allowing the run lengths (always the same constant) to be a constant hunk-sized array, whose values all equal the size of an index block. * Possible optimization: Alternately, it may turn out to be faster to compress the primitive index into "runs", each consisting of contiguous primitives within the hunk. * If the primitives in a GLPrimitiveSet are in multiple VBO hunks, there will be multiple IBO handles in the GLPrimitiveSet. While drawing, each one gets a glMultiDrawElements call, with the relevant VBO hunk arrays enabled in the GL. """ import graphics.drawing.drawing_constants as drawing_constants import graphics.drawing.drawing_globals as drawing_globals from OpenGL.GL import glPushMatrix, glPopMatrix class GLPrimitiveSet: """ Cached data structure for rapidly drawing a set of CSDLs. It collects their shader primitives (of various kinds), color-sorted DLs, and anything else they might have for immediate-mode OpenGL drawing (nothing as of 090311), into a structure that can be rapidly redrawn multiple times. @note: this needs to be remade from scratch if its set of CSDLs, or any of its CSDLs' contents or properties, changes. @todo: provisions for incremental modification. """ def __init__(self, csdl_list): """ """ self.CSDLs = csdl_list # Collect lists of primitives to draw in batches, and those CSDLs with # display lists to draw as well. (A given CSDL may have both.) self.spheres = [] # Generalize to a dict of lists? self.cylinders = [] self._CSDLs_with_nonshader_drawing = [] #bruce 090312 renamed this from CSDLs_with_DLs, # since the logic herein only cares that they have some sort of # drawing to do in immediate-mode OpenGL, not how it's done. # # (todo, in future: split this into whatever can be compiled # into an overall DL of our own (meaning it never changes and # is all legal while compiling a DL -- in particular, it can call # other DLs but it can't recompile them), and whatever really has # to be done in immediate mode and perhaps recomputed on each # draw, as a further optimization. This requires splitting # each of the associated CSDL API methods, has_nonshader_drawing # and .draw(..., draw_shader_primitives = False, # transform_nonshaders = False ). # If that's done, draw the immediate-mode-parts first here, in case # any of them also want to recompile DLs which are called in the # ok-for-inside-one-big-DL parts.) for csdl in self.CSDLs: self.spheres += csdl.spheres self.cylinders += csdl.cylinders if csdl.has_nonshader_drawing(): self._CSDLs_with_nonshader_drawing += [csdl] pass continue self.drawIndices = {} # Generated on demand. # Support for lazily updating drawing caches, namely a # timestamp showing when this GLPrimitiveSet was created. self.created = drawing_constants.eventStamp() # optimization: sort _CSDLs_with_nonshader_drawing by their transformControl. # [bruce 090225] items = [(id(csdl.transformControl), csdl) for csdl in self._CSDLs_with_nonshader_drawing] items.sort() self._CSDLs_with_nonshader_drawing = [csdl for (junk, csdl) in items] return def draw(self, highlighted = False, selected = False, patterning = True, highlight_color = None, opacity = 1.0 ): """ Draw the cached display. @note: all arguments are sometimes passed positionally. @note: opacity other than 1.0 is not yet implemented. """ # Draw shader primitives from CSDLs through shaders # (via GLPrimitiveBuffers, one per kind of shader), # if that's turned on. primlist_buffer_pairs = [] if self.spheres: # note: similar code exists in CSDL. primlist_buffer_pairs += [(self.spheres, drawing_globals.sphereShaderGlobals.primitiveBuffer)] pass if self.cylinders: primlist_buffer_pairs += [(self.cylinders, drawing_globals.cylinderShaderGlobals.primitiveBuffer)] pass for primitives, primbuffer in primlist_buffer_pairs: if len(primitives) > 0: if True: # False ## True: indexed drawing, False: unindexed. # Generate and cache index lists for selective drawing # of primitives through glMultiDrawElements(). if primbuffer not in self.drawIndices: self.drawIndices[primbuffer] = primbuffer.makeDrawIndex(primitives) pass # With a drawIndex, draw calls glMultiDrawElements(). primbuffer.draw(self.drawIndices[primbuffer], highlighted, selected, patterning, highlight_color, opacity) else: # (For initial testing.) Here GLPrimitiveBuffer draws the # entire set of sphere primitives using glDrawElements(). primbuffer.draw() pass pass continue # Draw just the non-shader drawing (e.g. color-sorted display lists), # in all CSDLs which have any. # Put TransformControl matrices onto the GL matrix stack when present. # (Pushing/popping is minimized by sorting the cached CSDL's earlier.) # [algorithm revised by bruce 090203] lastTC = None for csdl in self._CSDLs_with_nonshader_drawing: tc = csdl.transformControl if tc is not lastTC: if lastTC is not None: glPopMatrix() pass if tc is not None: glPushMatrix() tc.applyTransform() pass lastTC = tc pass # just draw non-shader stuff, and ignore csdl.transformControl csdl.draw( highlighted, selected, patterning, highlight_color, draw_shader_primitives = False, transform_nonshaders = False ) continue if lastTC is not None: glPopMatrix() return pass # end of class GLPrimitiveSet # end
NanoCAD-master
cad/src/graphics/drawing/GLPrimitiveSet.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ c_renderer.py - Interface to the experimental C++ renderer: - quux_module_import_succeeded (boolean) - classes for the ColorSorter's arrays of C++ primitives to draw; does some memoization as a speedup. WARNING: this has not been maintained for a long time, and has not been tested after at least two major refactorings, one on 090303. But it once worked and might be useful as example code, so it's being kept around for now. @author: Brad G, Will @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Brad G wrote much of this in drawer.py. I think Will modified the quux init code at some point. 080519 russ pulled the globals into a drawing_globals module and broke drawer.py into 10 smaller chunks: glprefs.py setup_draw.py shape_vertices.py ColorSorter.py CS_workers.py c_renderer.py CS_draw_primitives.py drawers.py gl_lighting.py gl_buffers.py 090303 Bruce refactored it. """ import foundation.env as env #bruce 051126 import utilities.EndUser as EndUser import sys import os import Numeric # these are used only by the test code at the bottom; # if these ever cause an import cycle, move that code to a separate module. from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushMatrix from OpenGL.GL import glTranslate from utilities.Log import redmsg from utilities.debug import print_compact_stack # == # Machinery to load the C renderer, from either of two places, # one for developers and one for end users. if EndUser.getAlternateSourcePath() != None: sys.path.append(os.path.join( EndUser.getAlternateSourcePath(), "experimental/pyrex-opengl")) else: sys.path.append("./experimental/pyrex-opengl") binPath = os.path.normpath(os.path.dirname(os.path.abspath(sys.argv[0])) + '/../bin') if binPath not in sys.path: sys.path.append(binPath) quux_module_import_succeeded = False try: import quux # can't be toplevel quux_module_import_succeeded = True if "experimental" in os.path.dirname(quux.__file__): # Should never happen for end users, but if it does we want to print the # warning. if env.debug() or not EndUser.enableDeveloperFeatures(): print "debug: fyi:", \ "Loaded experimental version of C rendering code:", \ quux.__file__ except: quux = None quux_module_import_succeeded = False if env.debug(): #bruce 060323 added condition print "WARNING: unable to import C rendering code (quux module).", \ "Only Python rendering will be available." pass # == class ShapeList_inplace: """ Records sphere and cylinder data and invokes it through the native C++ rendering system. This has the benefit over ShapeList that shapes aren't first stored in lots of Python lists, and then turned into lots of Numeric arrays. Instead, it stores directly in a list of fixed-size Numeric arrays. It shows some speedup, but not a lot. And tons of memory is being used. I'm not sure where. -grantham """ __author__ = "grantham@plunk.org" _blocking = 512 # balance between memory zeroing and drawing efficiency def __init__(self): # # Lists of lists, each list containing a Numeric array and the # number of objects in that array. E.g. Each element in # sphere is [l, n], where l is array((m, 9), 'f'), n is the # number of valid 9 element slices in l that represent # spheres, and m is equal to or more than n+1. # self.spheres = [] self.cylinders = [] # If this is true, disallow future adds. self.petrified = False def draw(self): """ Draw all the objects represented in this shape list. """ for (spheres, count) in self.spheres: quux.shapeRendererDrawSpheresIlvd(count, spheres) for (cylinders, count) in self.cylinders: quux.shapeRendererDrawCylindersIlvd(count, cylinders) def add_sphere(self, color4, pos, radius, name = 0): """ Add a sphere to this shape list. "color4" must have 4 elements. "name" is the GL selection name. """ if self.petrified: raise ValueError, \ "Tried to add a sphere to a petrified ShapeList_inplace" # struct Sphere { # float m_color[4]; # float m_nameUInt; # float m_center[3]; # float m_radius; # }; if (len(self.spheres) == 0 or self.spheres[-1][1] == ShapeList_inplace._blocking): # size of struct Sphere in floats is 9 block = Numeric.zeros((ShapeList_inplace._blocking, 9), 'f') self.spheres.append([block, 0]) (block, count) = self.spheres[-1] block[count] = (\ color4[0], color4[1], color4[2], color4[3], float(name), pos[0], pos[1], pos[2], radius) self.spheres[-1][1] += 1 def add_cylinder(self, color4, pos1, pos2, radius, name = 0, capped=0): """ Add a cylinder to this shape list. "color4" must have 4 elements. "name" is the GL selection name. """ if self.petrified: raise ValueError, \ "Tried to add a cylinder to a petrified ShapeList_inplace" # struct Cylinder { # float m_color[4]; # float m_nameUInt; # float m_cappedBool; # float m_pos1[3]; # float m_pos2[3]; # float m_radius; # }; if (len(self.cylinders) == 0 or self.cylinders[-1][1] == ShapeList_inplace._blocking): # size of struct Cylinder in floats is 13 block = Numeric.zeros((ShapeList_inplace._blocking, 13), 'f') self.cylinders.append([block, 0]) (block, count) = self.cylinders[-1] block[count] = (\ color4[0], color4[1], color4[2], color4[3], float(name), float(capped), pos1[0], pos1[1], pos1[2], pos2[0], pos2[1], pos2[2], radius) self.cylinders[-1][1] += 1 def petrify(self): """ Make this object Since the last block of shapes might not be full, this function copies them to a new block exactly big enough to hold the shapes in that block. The gc has a chance to release the old block and reduce memory use. After this point, shapes must not be added to this ShapeList. """ self.petrified = True if len(self.spheres) > 0: count = self.spheres[-1][1] if count < ShapeList_inplace._blocking: block = self.spheres[-1][0] newblock = Numeric.array(block[0:count], 'f') self.spheres[-1][0] = newblock if len(self.cylinders) > 0: count = self.cylinders[-1][1] if count < ShapeList_inplace._blocking: block = self.cylinders[-1][0] newblock = Numeric.array(block[0:count], 'f') self.cylinders[-1][0] = newblock pass # == class ShapeList: # not used as of before 090303 """ Records sphere and cylinder data and invokes it through the native C++ rendering system. Probably better to use "ShapeList_inplace". """ __author__ = "grantham@plunk.org" def __init__(self): self.memoized = False self.sphere_colors = [] self.sphere_radii = [] self.sphere_centers = [] self.sphere_names = [] self.cylinder_colors = [] self.cylinder_radii = [] self.cylinder_pos1 = [] self.cylinder_pos2 = [] self.cylinder_cappings = [] self.cylinder_names = [] def _memoize(self): """ Internal function that creates Numeric arrays from the data stored in add_sphere and add-cylinder. """ self.memoized = True # GL Names are uint32. Numeric.array appears to have only # int32. Winging it... self.sphere_colors_array = Numeric.array(self.sphere_colors, 'f') self.sphere_radii_array = Numeric.array(self.sphere_radii, 'f') self.sphere_centers_array = Numeric.array(self.sphere_centers, 'f') self.sphere_names_array = Numeric.array(self.sphere_names, 'i') self.cylinder_colors_array = Numeric.array(self.cylinder_colors, 'f') self.cylinder_radii_array = Numeric.array(self.cylinder_radii, 'f') self.cylinder_pos1_array = Numeric.array(self.cylinder_pos1, 'f') self.cylinder_pos2_array = Numeric.array(self.cylinder_pos2, 'f') self.cylinder_cappings_array = Numeric.array(self.cylinder_cappings,'f') self.cylinder_names_array = Numeric.array(self.cylinder_names, 'i') def draw(self): """ Draw all the objects represented in this shape list. """ # ICK - SLOW - Probably no big deal in a display list. if len(self.sphere_radii) > 0: if not self.memoized: self._memoize() quux.shapeRendererDrawSpheres(len(self.sphere_radii), self.sphere_centers_array, self.sphere_radii_array, self.sphere_colors_array, self.sphere_names_array) if len(self.cylinder_radii) > 0: if not self.memoized: self._memoize() quux.shapeRendererDrawCylinders(len(self.cylinder_radii), self.cylinder_pos1_array, self.cylinder_pos2_array, self.cylinder_radii_array, self.cylinder_cappings_array, self.cylinder_colors_array, self.cylinder_names_array) def add_sphere(self, color4, pos, radius, name = 0): """ Add a sphere to this shape list. "color4" must have 4 elements. "name" is the GL selection name. """ self.sphere_colors.append(color4) self.sphere_centers.append(list(pos)) self.sphere_radii.append(radius) self.sphere_names.append(name) self.memoized = False def add_cylinder(self, color4, pos1, pos2, radius, name = 0, capped=0): """ Add a cylinder to this shape list. "color4" must have 4 elements. "name" is the GL selection name. """ self.cylinder_colors.append(color4) self.cylinder_radii.append(radius) self.cylinder_pos1.append(list(pos1)) self.cylinder_pos2.append(list(pos2)) self.cylinder_cappings.append(capped) self.cylinder_names.append(name) self.memoized = False def petrify(self): """ Delete all but the cached Numeric arrays. Call this when you're sure you don't have any more shapes to store in the shape list and you want to release the python lists of data back to the heap. Additional shapes must not be added to this shape list. """ if not self.memoized: self._memoize() del self.sphere_colors del self.sphere_radii del self.sphere_centers del self.sphere_names del self.cylinder_colors del self.cylinder_radii del self.cylinder_pos1 del self.cylinder_pos2 del self.cylinder_cappings del self.cylinder_names pass # == def test_pyrex_opengl(test_type): # not tested since major refactoring try: print_compact_stack("selectMode Draw: " )### ### BUG: if import quux fails, we get into some sort of infinite ### loop of Draw calls. [bruce 070917 comment] #self.w.win_update() ## sys.path.append("./experimental/pyrex-opengl") # no longer ##needed here -- always done in drawer.py binPath = os.path.normpath(os.path.dirname( os.path.abspath(sys.argv[0])) + '/../bin') if binPath not in sys.path: sys.path.append(binPath) import quux if "experimental" in os.path.dirname(quux.__file__): print "WARNING: Using experimental version of quux module" # quux.test() quux.shapeRendererInit() quux.shapeRendererSetUseDynamicLOD(0) quux.shapeRendererStartDrawing() if test_type == 1: center = Numeric.array((Numeric.array((0, 0, 0), 'f'), Numeric.array((0, 0, 1), 'f'), Numeric.array((0, 1, 0), 'f'), Numeric.array((0, 1, 1), 'f'), Numeric.array((1, 0, 0), 'f'), Numeric.array((1, 0, 1), 'f'), Numeric.array((1, 1, 0), 'f'), Numeric.array((1, 1, 1), 'f')), 'f') radius = Numeric.array((0.2, 0.4, 0.6, 0.8, 1.2, 1.4, 1.6, 1.8), 'f') color = Numeric.array((Numeric.array((0, 0, 0, 0.5), 'f'), Numeric.array((0, 0, 1, 0.5), 'f'), Numeric.array((0, 1, 0, 0.5), 'f'), Numeric.array((0, 1, 1, 0.5), 'f'), Numeric.array((1, 0, 0, 0.5), 'f'), Numeric.array((1, 0, 1, 0.5), 'f'), Numeric.array((1, 1, 0, 0.5), 'f'), Numeric.array((1, 1, 1, 0.5), 'f')), 'f') result = quux.shapeRendererDrawSpheres(8, center, radius, color) elif test_type == 2: # grantham - I'm pretty sure the actual compilation, init, # etc happens once from bearing_data import sphereCenters, sphereRadii from bearing_data import sphereColors, cylinderPos1 from bearing_data import cylinderPos2, cylinderRadii from bearing_data import cylinderCapped, cylinderColors glPushMatrix() glTranslate(-0.001500, -0.000501, 151.873627) result = quux.shapeRendererDrawSpheres(1848, sphereCenters, sphereRadii, sphereColors) result = quux.shapeRendererDrawCylinders(5290, cylinderPos1, cylinderPos2, cylinderRadii, cylinderCapped, cylinderColors) glPopMatrix() quux.shapeRendererFinishDrawing() except ImportError: env.history.message(redmsg( "Can't import Pyrex OpenGL or maybe bearing_data.py, rebuild it")) return # end
NanoCAD-master
cad/src/graphics/drawing/c_renderer.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ ColorSortedDisplayList.py - A set of primitives to be drawn as a unit, under runtime-determined drawing styles @author: Russ @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: This was originally written by Russ in ColorSorter.py. See that file for its pre-090220 history. bruce 090220 added reentrancy, split it into this file. bruce 090312 generalizing API (and soon, functionality) to support other kinds of non-shader drawing besides color-sorted DLs. TODO: Change ColorSorter into a normal class with distinct instances. Give it a stack of instances rather than its current _suspend system. Refactor some things between ColorSorter and ColorSortedDisplayList (which needs renaming). [bruce 090220 comment] """ from OpenGL.GL import GL_COMPILE from OpenGL.GL import glNewList from OpenGL.GL import glEndList from OpenGL.GL import glCallList from OpenGL.GL import glDeleteLists from OpenGL.GL import glGenLists from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GL import glDisable from OpenGL.GL import glEnable from OpenGL.GL import glPushName from OpenGL.GL import glPopName from OpenGL.GL import glColor3fv from OpenGL.GL import GL_LIGHTING from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import hoverHighlightingColorStyle_prefs_key from utilities.prefs_constants import HHS_HALO from utilities.prefs_constants import selectionColor_prefs_key from utilities.prefs_constants import selectionColorStyle_prefs_key from utilities.prefs_constants import SS_HALO from utilities.debug import print_compact_traceback import foundation.env as env from graphics.drawing.CS_workers import drawpolycone_multicolor_worker from graphics.drawing.CS_workers import drawpolycone_worker from graphics.drawing.CS_workers import drawtriangle_strip_worker from graphics.drawing.patterned_drawing import isPatternedDrawing from graphics.drawing.patterned_drawing import startPatternedDrawing from graphics.drawing.patterned_drawing import endPatternedDrawing import graphics.drawing.drawing_constants as drawing_constants import graphics.drawing.drawing_globals as drawing_globals from graphics.drawing.gl_lighting import apply_material # == _csdl_id_counter = 0 _warned_del = False # == class ColorSortedDisplayList: #Russ 080225: Added. """ The ColorSorter's parent uses one of these to store color-sorted display list state. It's passed in to ColorSorter.start() . CSDLs are now created with a TransformControl reference as an argument (and are internally listed in it while they exist). This TransformControl reference is constant (although the transform in the TransformControl is mutable). For convenience, the TransformControl argument can be left out if you don't want to use a TransformControl to move the CSDL. This has the same effect as giving a TransformControl whose transform remains as the identity matrix. @note: as of 090223, the transformControl can also be a Chunk. Details to be documented later. """ # default values of instance variables [note: incomplete] ### todo: some of these and/or the dl variables not listed here # could be renamed to indicate that they are private. transformControl = None # might be a TransformControl or a Chunk reentrant = False #bruce 090220 _transform_id = None #bruce 090223 _untransformed_data = None #bruce 090223 spheres = () #bruce 090224 cylinders = () #bruce 090224 _drawing_funcs = () #bruce 090312 def __init__(self, transformControl = None, reentrant = False): """ """ self._clear_when_deallocate_DLs_might_be_unsafe() #bruce 090224 moved this earlier, made it do more, # removed inits from this method which are now redundant if reentrant: self.reentrant = True # permits reentrant ColorSorter.start # [Russ 080915: Added. # A unique integer ID for each CSDL. global _csdl_id_counter _csdl_id_counter += 1 self.csdl_id = _csdl_id_counter # Support for lazily updating drawing caches, namely a # timestamp showing when this CSDL was last changed. self.changed = drawing_constants.eventStamp() if transformControl is not None: self.transformControl = transformControl try: ##### KLUGE (temporary), for dealing with a perhaps-permanent change: # transformControl might be a Chunk, # which has (we assume & depend on) no transform_id _x = self.transformControl.transform_id # should fail for Chunk except AttributeError: # Assume transformControl is a Chunk. # Note: no point in doing self.updateTransform() yet (to record # untransformed data early) -- we have no data, since no # shader primitives have been stored yet. Untransformed data # will be recorded the first time it's transformed (after init, # and after each time primitives get cleared and remade). pass else: assert _x is not None assert _x is not -1 self._transform_id = _x pass # CSDLs should not have a glname since they are never a selobj. # Any testCases which depend on this should be rewritten. # [bruce 090311] ## # Russ 081122: Mark CSDLs with a glname for selection. ## # (Note: this is a temporary kluge for testing. [bruce 090223 comment]) ## self.glname = env._shared_glselect_name_dict. \ ## alloc_my_glselect_name(self) ## ###self.glname = 0x12345678 ### For testing. # Whether to draw in the selection over-ride color. self.selected = False ### TODO [bruce 090114 comment]: a near-term goal is to remove # self.selected and self.dl, so that self only knows # how to draw either way, but always finds out as-needed # (from client state) which way to actually draw. # Reviewing the current code, I think the only remaining # essential use of self.dl is in CrystalShape.py # (see new comment in its docstring for how to clean that up), # and the only remaining essential use of self.selected # (aside from maintaining self.dl, no longer needed if it's removed) # is in ColorSorter.finish (which should be replaced by # passing finish the same drawing-style arguments that # CSDL.draw accepts). return def __repr__(self): #bruce 090224 name = self.__class__.__name__.split('.')[-1] if self.transformControl: return "<%s at %#x for %r>" % (name, id(self), self.transformControl) else: return "<%s at %#x>" % (name, id(self)) pass # Russ 080925: Added. def transform_id(self): """ Return the transform_id of the CSDL, or None if there is no associated TransformControl (including if self.transformControl is not an instance of TransformControl). """ return self._transform_id def has_nonempty_DLs(self): #bruce 090225 [090312: maybe inline all uses and remove from API] """ Are any of our toplevel OpenGL display lists nonempty (i.e. do they have any drawing effect)? @note: This test is useful, since we build all our toplevel display lists even if they are empty, due to some client code which may require this. When shaders are turned on, having all DLs empty will be common. """ return bool( self._per_color_dls) def has_nonshader_drawing(self): #bruce 090312 """ Do we have any drawing to do other than shader primitives? """ # (see comments in GLPrimitiveSet for how this might evolve further) return self.has_nonempty_DLs() or self._drawing_funcs # == def start(self, pickstate): #bruce 090224 split this out of caller """ Clear self and start collecting new primitives for use inside it. (They are collected by staticmethods in the ColorSorter singleton class, and saved partly in ColorSorter class attributes, partly in self by direct assignment (maybe not anymore), and partly in self by methods ColorSorter calls in self.) [meant to be called only by ColorSorter.start, for now] """ if pickstate is not None: # todo: refactor to remove this deprecated argument ### review: is it correct to not reset self.selected when this is None?? self.selectPick(pickstate) pass # Russ 080915: This supports lazily updating drawing caches. self.changed = drawing_constants.eventStamp() # Clear the primitive data to start collecting a new set. # REVIEW: is it good that we don't also deallocate DLs here? # Guess: yes if we reuse them, no if we don't. # It looks like finish calls _reset, which deallocates them, # so we might as well do that right here instead. Also, that # way I can remove _reset from finish, which is good since # I've made _reset clearPrimitives, which is a bug if done # in finish (when were added between start and finish). # [bruce 090224 comment and revision] ## self._clearPrimitives() self._reset() if 0: # keep around, in case we want a catchall DL in the future #bruce 090114 removed support for # [note: later: these are no longer in drawing_globals] # (not (drawing_globals.allow_color_sorting and # drawing_globals.use_color_sorted_dls)): # This is the beginning of the single display list created when # color sorting is turned off. It is ended in # ColorSorter.finish . In between, the calls to # draw{sphere,cylinder,polycone} methods pass through # ColorSorter.schedule_* but are immediately sent to *_worker # where they do OpenGL drawing that is captured into the display # list. try: if self.dl == 0: self.activate() # Allocate a display list for our use. pass # Start a single-level list. glNewList(self.dl, GL_COMPILE) except: print ("data related to following exception: self.dl = %r" % (self.dl,)) #bruce 070521 raise pass return # == def finish(self, sorted_by_color): #bruce 090224 split this out of caller """ Finish collecting new primitives for use in self, and store them all in self, ready to be drawn in various ways. [meant to be called only by ColorSorter.start, for now] """ ## self._reset() ## # (note: this deallocates any existing display lists) if self.transformControl and (self.spheres or self.cylinders): self.updateTransform() # needed to do the transform for the first time, # even if it didn't change. Review: refactor to # whereever we first compile these down? That # might be a different place in self.draw vs. # draw from DrawingSet. selColor = env.prefs[selectionColor_prefs_key] # Note: if sorted_by_color is empty, current code still builds all # toplevel display lists, though they are noops. This may be needed # by some client code which uses those dls directly. Client code # wanting to know if it needs to draw our dls should test # self.has_nonempty_DLs(), which tests self._per_color_dls, # or self.has_nonshader_drawing(), which reports on that or any # other kind of nonshader (immediate mode opengl) drawing we might # have. [bruce 090225/090312 comment] # First build the lower level per-color sublists of primitives. for color, funcs in sorted_by_color.iteritems(): sublists = [glGenLists(1), 0] # Remember the display list ID for this color. self._per_color_dls.append([color, sublists]) glNewList(sublists[0], GL_COMPILE) opacity = color[3] if opacity == -1: #russ 080306: "Unshaded colors" for lines are signaled # by an opacity of -1 (4th component of the color.) glDisable(GL_LIGHTING) # Don't forget to re-enable it! pass for func, params, name in funcs: if name: glPushName(name) else: pass ## print "bug_2: attempt to push non-glname", name func(params) # Call the draw worker function. if name: glPopName() pass continue if opacity == -1: # Enable lighting after drawing "unshaded" objects. glEnable(GL_LIGHTING) pass glEndList() if opacity == -2: # piotr 080419: Special case for drawpolycone_multicolor # create another display list that ignores # the contents of color_array. # Remember the display list ID for this color. sublists[1] = glGenLists(1) glNewList(sublists[1], GL_COMPILE) for func, params, name in funcs: if name: glPushName(name) else: pass ## print "bug_3: attempt to push non-glname", name if func == drawpolycone_multicolor_worker: # Just to be sure, check if the func # is drawpolycone_multicolor_worker # and call drawpolycone_worker instead. # I think in the future we can figure out # a more general way of handling the # GL_COLOR_MATERIAL objects. piotr 080420 pos_array, color_array_junk, rad_array = params drawpolycone_worker((pos_array, rad_array)) elif func == drawtriangle_strip_worker: # piotr 080710: Multi-color modification # for triangle_strip primitive (used by # reduced protein style). pos_array, normal_array, color_array_junk = params drawtriangle_strip_worker((pos_array, normal_array, None)) if name: glPopName() pass continue glEndList() continue # Now the upper-level lists call all of the per-color sublists. #### REVIEW: these are created even when empty. Is that necessary? # [bruce 090224 Q] # One with colors. color_dl = self.color_dl = glGenLists(1) glNewList(color_dl, GL_COMPILE) for color, dls in self._per_color_dls: opacity = color[3] if opacity < 0: #russ 080306: "Unshaded colors" for lines are signaled # by a negative alpha. glColor3fv(color[:3]) # piotr 080417: for opacity == -2, i.e. if # GL_COLOR_MATERIAL is enabled, the color is going # to be ignored, anyway, so it is not necessary # to be tested here else: apply_material(color) glCallList(dls[0]) continue glEndList() # A second one without any colors. nocolor_dl = self.nocolor_dl = glGenLists(1) glNewList(nocolor_dl, GL_COMPILE) for color, dls in self._per_color_dls: opacity = color[3] if opacity == -2 \ and dls[1] > 0: # piotr 080420: If GL_COLOR_MATERIAL is enabled, # use a regular, single color dl rather than the # multicolor one. Btw, dls[1] == 0 should never # happen. glCallList(dls[1]) else: glCallList(dls[0]) glEndList() # A third DL implements the selected appearance. selected_dl = self.selected_dl = glGenLists(1) glNewList(selected_dl, GL_COMPILE) # russ 080530: Support for patterned selection drawing modes. patterned = isPatternedDrawing(select = True) if patterned: # Patterned drawing needs the colored dl drawn first. glCallList(color_dl) startPatternedDrawing(select = True) pass # Draw solid color (unpatterned) or an overlay pattern, in the # selection color. apply_material(selColor) glCallList(nocolor_dl) if patterned: # Reset from patterning drawing mode. endPatternedDrawing(select = True) glEndList() pass # == # Russ 080925: For batched primitive drawing, drawing-primitive functions # conditionally collect lists of primitive IDs here in the CSDL, rather than # sending them down through the ColorSorter schedule methods into the DL # layer. Later, those primitive lists are collected across the CSDLs in # a DrawingSet, into the per-primitive-type VBO caches and MultiDraw indices # managed by its GLPrimitiveSet. Most of the intermediate stuff will be # cached in the underlying GLPrimitiveBuffer, since GLPrimitiveSet is meant # to be very transient. # # This can be factored when we get a lot of primitive shaders. For now, # simply cache the drawing-primitive IDs at the top level of CSDL. def addSphere(self, center, radius, color, glname): """ Allocate a shader sphere primitive (in the set of all spheres that are able to be drawn in this GL resource context), set up its drawing parameters, and add its primID to self's list of spheres (so it will be drawn when self is drawn, or included in DrawingSet drawing indices when they are drawn and include self). . center is a VQT point. . radius is a number. . color is a list of components: [R, G, B]. . glname comes from the _gl_name_stack. """ self.spheres += drawing_globals.sphereShaderGlobals.primitiveBuffer.addSpheres( [center], radius, color, self.transform_id(), glname) self._clear_derived_primitive_caches() return # Russ 090119: Added. def addCylinder(self, endpts, radii, color, glname): """ Like addSphere, but for cylinders. See addSphere docstring for details. . endpts is a tuple of two VQT points. . radii may be a single number, or a tuple of two radii for taper. . color is a list of components: [R, G, B] or [R, G, B, A]. . glname comes from the _gl_name_stack. """ self.cylinders += drawing_globals.cylinderShaderGlobals.primitiveBuffer.addCylinders( [endpts], radii, color, self.transform_id(), glname) self._clear_derived_primitive_caches() return # == def clear_drawing_funcs(self): self._drawing_funcs = () def add_drawing_func(self, func): if not self._drawing_funcs: self._drawing_funcs = [] self._drawing_funcs += [func] # == #### NOTE: the methods draw_in_abs_coords and nodes_containing_selobj # don't make sense in this class in the long run, since it is not meant # to be directly used as a "selobj" or as a Node. I presume they are # only needed by temporary testing and debugging code, and they should be # removed when no longer needed. [bruce 090114 comment] # # Update, bruce 090311: I'm removing them now (since we need to test the # claim that nothing but test code depends on them). Any testCases this # breaks should be rewritten to put their CSDLs inside wrapper objects # which provide these methods. # ## # Russ 081128: Used by preDraw_glselect_dict() in standard_repaint_0(), and ## # _draw_highlighted_selobj() in _do_other_drawing_inside_stereo(). ## def draw_in_abs_coords(self, glpane, color): ## self.draw(highlighted = True, highlight_color = color) ## return ## ## # Russ 081128: Used by GLPane._update_nodes_containing_selobj(). ## def nodes_containing_selobj(self): ## # XXX Only TestGraphics_GraphicsMode selects CSDL's now, so no ## # XXX connection to the Model Tree. ## return [] # == ##### TODO: FIX TERMINOLOGY BUG: # in the following three methodnames and all localvar names and comments # where they are used, replace shader with primitiveBuffer. [bruce 090303] def shaders_and_primitive_lists(self): #bruce 090218 """ Yield each pair of (primitiveBuffer, primitive-list) which we need to draw. """ if self.spheres: assert drawing_globals.sphereShaderGlobals.primitiveBuffer yield drawing_globals.sphereShaderGlobals.primitiveBuffer, self.spheres if self.cylinders: assert drawing_globals.cylinderShaderGlobals.primitiveBuffer yield drawing_globals.cylinderShaderGlobals.primitiveBuffer, self.cylinders return def shader_primID_pairs(self): #bruce 090223 for shader, primitives in self.shaders_and_primitive_lists(): for p in primitives: yield shader, p return def draw_shader_primitives(self, *args): #bruce 090218, needed only for CSDL.draw for shader, primitives_junk in self.shaders_and_primitive_lists(): index = self.drawIndices[shader] shader.draw(index, *args) continue return def updateTransform(self): #bruce 090223 """ Update transformed version of cached coordinates, using the current transform value of self.transformControl. This should only be called if transformControl was provided to__init__, and must be called whenever its transform value changes, sometime before we are next drawn. @note: in current implem, this is only needed if self is drawn using shader primitives, and may only work properly if self.transformControl is a Chunk. """ try: s_p_pairs = list(self.shader_primID_pairs()) if not s_p_pairs: # optimization return if not self._untransformed_data: # save untransformed data here for reuse (format depends on shader) _untransformed_data = [] # don't retain this in self until it's all collected # (otherwise we get confusing bugs from its being too short, # if there's an exception while collecting it) for shader, p in s_p_pairs: ut = shader.grab_untransformed_data(p) _untransformed_data += [ut] continue self._untransformed_data = _untransformed_data # print "remade len %d of utdata in" % len(self._untransformed_data), self assert len(self._untransformed_data) == len( s_p_pairs ) assert s_p_pairs == list(self.shader_primID_pairs()) # this could fail if shader_primID_pairs isn't deterministic # or if its value gets modified while collecting it # (either scenario would be a bug) pass else: # print "found %d utdata in" % len(self._untransformed_data), self assert len(self._untransformed_data) == len( s_p_pairs ) # this could fail if the length of s_p_pairs could vary # over time, without resets to self._untransformed_data # (which would be a bug) transform = self.transformControl for (shader, p), ut in zip( s_p_pairs , self._untransformed_data ): shader.store_transformed_primitive( p, ut, transform) continue pass except: # might as well skip the update but not mess up anything else # being drawn at the same time (this typically runs during drawing) msg = "bug: ignoring exception in updateTransform in %r" % self print_compact_traceback(msg + ": ") return def draw(self, highlighted = False, selected = False, patterning = True, highlight_color = None, draw_shader_primitives = True, #bruce 090312 renamed from draw_primitives transform_nonshaders = True, #bruce 090312 renamed from transform_DLs ): """ Simple all-in-one interface to CSDL drawing. Allocate a CSDL in the parent class and fill it with the ColorSorter: self.csdl = ColorSortedDisplayList() ColorSorter.start(glpane, self.csdl) drawsphere(...), drawcylinder(...), drawpolycone(...), and so on. ColorSorter.finish() Then when you want to draw the display lists call csdl.draw() with the desired options: @param highlighted: Whether to draw highlighted. @param selected: Whether to draw selected. @param patterning: Whether to apply patterned drawing styles for highlighting and selection, according to the prefs settings. If not set, it's as if the solid-color prefs are chosen. @param highlight_color: Option to over-ride the highlight color set in the color scheme preferences. @param draw_shader_primitives: Whether to draw our shader primitives. Defaults to True. @param transform_nonshaders: Whether to apply self.transformControl to our non-shader drawing (such as DLs). Defaults to True. """ patterned_highlighting = (patterning and isPatternedDrawing(highlight = highlighted)) halo_selection = (selected and env.prefs[selectionColorStyle_prefs_key] == SS_HALO) halo_highlighting = (highlighted and env.prefs[hoverHighlightingColorStyle_prefs_key] == HHS_HALO) # KLUGES which should be replaced by our having suitable new attrs, # such as glpane or glprefs or glresourcecontext (replacing drawing_globals): drawing_phase = drawing_globals.drawing_phase # kluge in CSDL.draw # (the other kluge is not having glpane.glprefs to pass to apply_material, # in draw; we do have glpane in finish but no point in using it there # until we have it in .draw too, preferably by attr rather than arg # (should review that opinion).) # Russ 081128 (clarified, bruce 090218): # # GLPrimitiveSet.draw() calls this method (CSDL.draw) on the CSDLs # in its _CSDLs_with_nonshader_drawing attribute (a list of CSDLs), # passing draw_shader_primitives = False to only draw the DLs, and # transform_nonshaders = False to avoid redundantly applying their # TransformControls. # # It gathers the shader primitives in a set of CSDLs into one big # drawIndex per primitive type, and draws each drawIndex in a big batch. # # This method (CSDL.draw) is also called to # draw *both* DLs and primitives in a CSDL, e.g. for hover-highlighting. # # Russ 081208: Skip drawing shader primitives while in GL_SELECT. # # Bruce 090218: support cylinders too. prims_to_do = (drawing_phase != "glselect" and draw_shader_primitives and (self.spheres or self.cylinders)) if prims_to_do: # Cache drawing indices for just the primitives in this CSDL, # in self.drawIndices, used in self.draw_shader_primitives below. if not self.drawIndices: for shader, primitives in self.shaders_and_primitive_lists(): self.drawIndices[shader] = shader.makeDrawIndex(primitives) continue pass pass if self._drawing_funcs and drawing_phase != "glselect_glname_color": #bruce 090312 # These ignore our drawing-style args; # they also are cleared independently of start/finish, # and changing them doesn't set our last-changed timestamp. # All this is intentional. (Though we might decide to add a kind # which does participate in patterned drawing; this might require # supplying more than one func, or a dict of colors and nocolor # funcs....) if self.transformControl and transform_nonshaders: glPushMatrix() self.transformControl.applyTransform() for func in self._drawing_funcs: try: func() except: msg = "bug: exception in drawing_func %r in %r, skipping it" % (func, self) print_compact_traceback(msg + ": ") pass continue if self.transformControl and transform_nonshaders: glPopMatrix() pass # Normal or selected drawing are done before a patterned highlight # overlay, and also when not highlighting at all. You'd think that when # we're drawing a solid highlight appearance, there'd be no need to draw # the normal appearance first, because it will be obscured by the # highlight. But halo selection extends beyond the object and is only # obscured by halo highlighting. [russ 080610] # Russ 081208: Skip DLs when drawing shader-prims with glnames-as-color. DLs_to_do = (drawing_phase != "glselect_glname_color" and self.has_nonempty_DLs()) # the following might be changed, then are used repeatedly below; # this simplifies the various ways we can handle transforms [bruce 090224] callList = glCallList # how to call a DL, perhaps inside our transform transform_once = False # whether to transform exactly once around the # following code (as opposed to not at all, or once per callList) if self.transformControl and transform_nonshaders: if prims_to_do and DLs_to_do: # shader primitives have transform built in, but DLs don't, # so we need to get in and out of local coords repeatedly # (once for each callList) during the following # (note similar code in DrawingSet.draw): [bruce 090224] callList = self._callList_inside_transformControl elif DLs_to_do: # we need to get into and out of local coords just once transform_once = True else: pass # nothing special needed for just shader prims (or nothing) pass if transform_once: glPushMatrix() self.transformControl.applyTransform() if (patterned_highlighting or not highlighted or (halo_selection and not halo_highlighting)) : if selected: # Draw the selected appearance. if prims_to_do: # Shader primitives. self.draw_shader_primitives( highlighted, selected, patterning, highlight_color) pass if DLs_to_do: # Display lists. # If the selection mode is patterned, the selected_dl does # first normal drawing and then draws an overlay. callList(self.selected_dl) pass pass else: # Plain, old, solid drawing of the base object appearance. if prims_to_do: self.draw_shader_primitives() # Shader primitives. pass if DLs_to_do: callList(self.color_dl) # Display lists. pass pass pass if highlighted: if prims_to_do: # Shader primitives. self.draw_shader_primitives( highlighted, selected, patterning, highlight_color) pass if DLs_to_do: # Display lists. if patterned_highlighting: # Set up a patterned drawing mode for the following draw. startPatternedDrawing(highlight = highlighted) pass # Draw a highlight overlay (solid, or in an overlay pattern.) if highlight_color is not None: hcolor = highlight_color else: hcolor = env.prefs[hoverHighlightingColor_prefs_key] apply_material(hcolor) callList(self.nocolor_dl) if patterned_highlighting: # Reset from a patterned drawing mode set up above. endPatternedDrawing(highlight = highlighted) pass pass pass if transform_once: glPopMatrix() return def _callList_inside_transformControl(self, DL): #bruce 090224 glPushMatrix() self.transformControl.applyTransform() glCallList(DL) glPopMatrix() return # == CSDL state maintenance def activate(self): """ Make a top-level display list id ready, but don't fill it in. """ ### REVIEW: after today's cleanup, I think this can no longer be called. # (Though it may be a logic bug that CrystalShape.py never calls it.) # [bruce 090114 comment] # Display list id for the current appearance. if not self.selected: self.color_dl = glGenLists(1) else: self.selected_dl = glGenLists(1) pass self.selectDl() #bruce 070521 added these two asserts assert type(self.dl) in (type(1), type(1L)) assert self.dl != 0 # This failed on Linux, keep checking. (bug 2042) return def selectPick(self, boolVal): """ Remember whether we're selected or not. """ self.selected = boolVal self.selectDl() return def selectDl(self): """ Change to either the normal-color display list or the selected one. """ self.dl = self.selected and self.selected_dl or self.color_dl return # == state clearing methods, also used to set up initial state # (should be refactored a bit more [bruce 090224 comment]) def _reset(self): """ Return to initialized state (but don't clear constructor parameters). Only legal when our GL context is current. """ #bruce 090224 revision: not worth the bug risk and maintenance issue # to figure out whether we have any state that needs clearing -- # so just always clear it all. self.deallocate_displists() return def deallocate_displists(self): """ Free any allocated display lists. (Also clear or initialize shader primitives and all other cached drawing state, but not constructor parameters.) @note: this is part of our external API. @see: _clear_when_deallocate_DLs_might_be_unsafe, which does all possible clearing *except* for deallocating display lists, for use when we're not sure deallocating them is safe. """ # With CSDL active, self.dl duplicates either selected_dl or color_dl. #bruce 090224 rewrote to make no assumptions about which DLs # are currently allocated or overlapping -- just delete all valid ones. DLs = {} for dl in [self.dl, self.color_dl, self.nocolor_dl, self.selected_dl]: DLs[dl] = dl # piotr 080420: The second level dl's are 2-element lists of DL ids # rather than just a list of ids. The second DL is used in case # of multi-color objects and is required for highlighting # and selection (not in rc1) for clr_junk, dls in self._per_color_dls: # Second-level dl's. for dl in dls: # iterate over DL pairs. DLs[dl] = dl for dl in DLs: if dl: # skip 0 or None (not sure if None ever happens) glDeleteLists(dl, 1) continue self._clear_when_deallocate_DLs_might_be_unsafe() return def _clear_when_deallocate_DLs_might_be_unsafe(self): """ Clear and initialize cached and stored drawing state (but not constructor parameters), except for deallocating OpenGL display lists. (In theory, this is safe to call even when our GL context is not current.) @note: this does not deallocate display lists. Therefore, it might be a VRAM memory leak if any DLs are allocated. So don't call it except via deallocate_displists, if possible. """ #bruce 090224 added _clearPrimitives, renamed, revised docstring self.dl = 0 # Current display list (color or selected.) self.color_dl = 0 # DL to set colors, call each lower level list. self.selected_dl = 0 # DL with a single (selected) over-ride color. self.nocolor_dl = 0 # DL of lower-level calls for color over-rides. self._per_color_dls = [] # Lower level, per-color primitive sublists. self._clearPrimitives() return def _clearPrimitives(self): """ Clear cached and stored drawing state related to shader primitives. """ # REVIEW: any reason to keep this separate from its caller, # _clear_when_deallocate_DLs_might_be_unsafe? Maybe other callers # can call that instead? For now, there are some calls for which # this is unclear, so I'm not merging them. [bruce 090224 comment] # Free them in the GLPrimitiveBuffers. # TODO: refactor to use self.shaders_and_primitive_lists(). #bruce 090224 revised conditions so they ignore current prefs if self.spheres: drawing_globals.sphereShaderGlobals.primitiveBuffer.releasePrimitives(self.spheres) if self.cylinders: drawing_globals.cylinderShaderGlobals.primitiveBuffer.releasePrimitives(self.cylinders) # Included drawing-primitive IDs. (These can be accessed more generally # using self.shaders_and_primitive_lists().) self.spheres = [] self.cylinders = [] self._clear_derived_primitive_caches() return def _clear_derived_primitive_caches(self): #bruce 090224 split this out """ Call this after modifying our lists of shader primitives. """ # Russ 081128: A cached primitives drawing index. This is only used # when drawing individual CSDLs for hover-highlighting, for testing, # and during development. Normally, # primitives from a number of CSDLs are collected into a GLPrimitiveSet # with a drawing index covering all of them. #bruce 090218: corrected above comment, and changed drawIndex -> # drawIndices so it can support more than one primitive type. self.drawIndices = {} self._untransformed_data = None return def __del__(self): # Russ 080915 """ Called by Python when an object is being freed. """ self.destroy() return def destroy(self): """ Free external resources and break reference cycles. """ # Free any OpenGL resources. ### REVIEW: Need to wait for our OpenGL context to become current when # GLPane calls its method saying it's current again. See chunk dealloc # code for details. This hangs NE1 now, so it's commented out. ## self.deallocate_displists() # Free primitives stored in VBO hunks. self._clearPrimitives() #bruce 090223 guess implem; would be redundant # with deallocate_displists if we called that here ## REVIEW: call _clear_when_deallocate_DLs_might_be_unsafe instead? # clear constructor parameters if they might cause reference cycles. self.transformControl = None #bruce 090223 return pass # end of class ColorSortedDisplayList # end
NanoCAD-master
cad/src/graphics/drawing/ColorSortedDisplayList.py
NanoCAD-master
cad/src/graphics/images/__init__.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ ImageUtils.py - Image utilities based on PIL. (Some doc of PIL can be found at http://www.pythonware.com/library/pil/handbook .) @author: Huaicai @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. History: 050930. Split off image utilities from drawer.py into this file. Mark 061127 some new features and docstrings by bruce """ import Image # This is from the PIL library import ImageOps import PngImagePlugin # Don't remove this, it is used by package creator to find right modules to support PNG image -- Huaicai # try to tell pylint we need to import PngImagePlugin [bruce 071023] PngImagePlugin from utilities import debug_flags #bruce 061127 from utilities.debug import print_compact_traceback #bruce 061128 class nEImageOps: """ Common image operations, such as get rgb data, flip, mirror, rotate, filter, resize, etc. Initialized from a filename readable by PIL. """ ## ideal_wd = ideal_ht = 256 # note: bruce 061127 renamed these to ideal_width, ideal_height, as public self attrs and __init__ options DESIRED_MODE = "RGBX" #bruce 061128 split this out def __init__(self, imageName, ideal_width = None, ideal_height = None, rescale = True, ##e filter = ... convert = False, _tmpmode = None, _debug = False): #bruce 061127 added options, self attrs, docstring; some are marked [untested] in docstring [###k need to test them]; ##e add options for resize filter choice, whether to use im.convert (experimental, nim), img mode to use for data (now RGBX) """ Create an nEImageOps object that holds a PIL image made from the given image filename, imageName. Not all file formats are supported; the file extension is not enough to know if the file is supported, since it also depends on the nature of the internal data (which is probably a bug that could be fixed). [#doc the convert option, which tries to address that [not fully tested], and the _tmpmode option.] The image will be resized on demand by getTextureData (but in place in this mutable object, thus affecting all subsequent queries too, not only queries via getTextureData), to ideal_width, ideal_height, specified as options, or if they're not supplied, by a debug_pref "image size", or by direct modification by client of self.ideal_width and self.ideal_height before this resizing is first done. (Callers which want no resizing to occur currently need to explicitly set self.ideal_width and self.ideal_height to the actual image size (before first calling getTextureData), which can be determined as explained below. Or, as of 'kluge070304', they can pass -1 for ideal_width and/or ideal_height to make them equal that dim of the native size. Note that this entire API is basically a kluge, and ought to be cleaned up sometime. ##e) For many OpenGL drivers, if the image will be used as texture data, these sizes need to be powers of two. The resizing will be done by rescaling, by default, or by padding on top and right if rescale = False. The original dimensions can be found in self.orig_width and self.orig_height [untested]; these never change after first reading the file (even when we internally reread the file in self.update, to work around bugs). The current dimensions can be found by knowing that width = self.img.size[0] and height = self.img.size[1]. If getTextureData has been called, these presumably equal the ideal dims, but I [bruce] don't know if this is always true. The PIL image object is stored in the semi-public attribute self.img, but this object often replaces that image with a new one, with altered data and/or size, either due to resizing for getTextureData, or to external calls of one of several image-modifying methods. """ self.debug = _debug #bruce 061204 self.imageName = imageName self.convert = convert self._tmpmode = _tmpmode #bruce 061128, probably temporary, needs doc if not; JPG illegal, JPEG doesn't work, TIFF works well self.img = Image.open(imageName) self.unconverted_img = self.img # for debugging, and in case keeping the python reference is needed if self.convert: #bruce 061128 # im.convert(mode) => image if type(self.convert) == type(""): mode = self.convert # let caller specify mode to convert to # Q: should this also affect getTextureData retval? if so, also reset self.DESIRED_MODE here. A: yes. #e [or maybe have a separate option, desired_mode or mode or convert_to? Guess: someday have that, # and the convert flag will go away since it will always be true, BUT the desired mode will be # a function of the original mode! (just as that will be the case with the desired size.)] if mode != self.DESIRED_MODE: # as of circa 070403 this happens routinely for convert = 'RGBA', and seems harmless... # if DESIRED_MODE was cleaned up as suggested above it'd probably be a historical relic; # so remove the debug print. [bruce 070404] ## print "%r: warning: convert = mode %r is not yet fully supported" % (self, self.convert) self.DESIRED_MODE = mode else: assert self.convert == True or self.convert == 1 mode = self.DESIRED_MODE old_data = self.img.size, self.img.mode self.img = self.img.convert(mode) #k does it matter whether we do this before or after resizing it? new_data = self.img.size, self.img.mode if old_data != new_data and debug_flags.atom_debug and self.debug: print "debug: %r: fyi: image converted from %r to %r" % (self, old_data, new_data) ###e also need self.update() in this case?? if so, better do it later during __init__. pass self.orig_width = self.img.size[0] #bruce 061127 self.orig_height = self.img.size[1] #bruce 061127 if debug_flags.atom_debug and self.debug: #bruce 061127; fyi, see also string in this file containing RGB print "debug fyi: nEImageOps.__init__: %r.img.size, mode is %r, %r" % (self, self.img.size, self.img.mode) ### if 1: #bruce 060213 - let debug pref set default values of ideal_width, ideal_height from utilities.debug_prefs import debug_pref, Choice self.ideal_width = self.ideal_height = debug_pref("image size", Choice([256,128,64,32,512,1024]), prefs_key = 'A8 devel/image size' ) #bruce 060612 made this persistent # these are not used until client code calls getTextureData; # it's ok if client modifies them directly before that, # anything from just once to before each call of getTextureData. if 1: #bruce 061127 - let caller override those values, and other behavior, using options if ideal_width is not None: self.ideal_width = ideal_width if ideal_height is not None: self.ideal_height = ideal_height self.rescale = rescale return def __repr__(self): #bruce 061127 #e add size & mode? if so, make sure it works in __init__ before self.img has been set! return "<%s at %#x for %r>" % (self.__class__.__name__, id(self), self.imageName) #e use basename only? def getPowerOfTwo(self, num): # [never reviewed by bruce] """ Returns the nearest number for <num> that's a power of 2. Currently, it's not used. """ assert(type(num) == type(1)) a = 0 # This proves that a large image may crash the program. This value works on my machine. H. maxValue = 256 oNum = num while num>1: num = num>>1 a += 1 s = min(1<<a, maxValue) ; b = min(1<<(a+1), maxValue) if (oNum-s) > (b-oNum): return b else: return s def getTextureData(self): #bruce 061127 revised API, implem and docstring """ Returns (width, height, data), where data contains the RGB values (required by OpenGL) of the image to be texture mapped onto a polygon. If self.rescale is false and if both image dims need to expand, the rgb pixels include padding which is outside the original image. Otherwise (including if one dim needs to expand and one to shrink), the image is stretched/shrunk to fit in each dim independently. """ if 'kluge070304': #bruce 070304 API kluge [works]: # permit -1 in ideal_width to indicate "use native width", and same for ideal_height. # (Note: it's difficult for an exprs.images.Image client to do the same without this kluge, # since orig_width is not available when ideal_width must be passed. It could do it by making one image, # examining it, then making another, though -- a bit inefficiently since two textures would be created.) if self.ideal_width == -1: self.ideal_width = self.orig_width if self.ideal_height == -1: self.ideal_height = self.orig_height ##e try using im.convert here... or as a new resize arg... or maybe in __init__ self.resize(self.ideal_width, self.ideal_height) # behavior depends on self.rescale # Notes: # - This is often called repeatedly; good thing it's fast # when size is already as requested (i.e. on all but the first call). # - self.resize used to ignore its arguments, but the same values given here were hardcoded internally. Fixed now. # [bruce 060212/061127 comments] width = self.img.size[0] height = self.img.size[1] try: rst = self.img.tostring("raw", self.DESIRED_MODE, 0, -1) # Note: this line can raise the exception "SystemError: unknown raw mode" for certain image files. # Maybe this could be fixed by using "im.convert(mode) => image" when loading the image?? ##e try it, see above for where [bruce 061127 comment] except: #bruce 061127 print "fyi: following exception relates to %r with mode %r" % (self.img, self.img.mode) #e also self.img.info? not sure if huge. raise #print "image size: ", width, height return width, height, rst def resize(self, wd, ht, filter = Image.BICUBIC): #e should self.rescale also come in as an arg? """ Resize image and filter it (or pad it if self.rescale is false and neither dimension needs to shrink). """ #e sometime try Image.ANTIALIAS to see if it's better quality; there are also faster choices. # For doc, see http://www.pythonware.com/library/pil/handbook/image.htm . # It says "Note that the bilinear and bicubic filters in the current version of PIL are not well-suited # for thumbnail generation. You should use ANTIALIAS unless speed is much more important than quality." # # Note: the arguments wd and ht were not used until bruce 061127 redefined this method to use them. # Before that, it acted as if self.ideal_width, self.ideal_height were always passed (as they in fact were). width = self.img.size[0] height = self.img.size[1] if (width, height) != (wd, ht): # actual != desired if self.rescale or wd < width or ht < height: # have to rescale if either dim needs to shrink # we will rescale. if not self.rescale: # print debug warning that it can't do as asked if debug_flags.atom_debug and self.debug: print "debug fyi: %r.resize is rescaling, tho asked not to, since a dim must shrink" % self #e more info self.img = self.img.resize( (wd, ht), filter) # supported filters, says doc: ##The filter argument can be one of NEAREST (use nearest neighbour), BILINEAR ##(linear interpolation in a 2x2 environment), BICUBIC (cubic spline ##interpolation in a 4x4 environment), or ANTIALIAS (a high-quality ##downsampling filter). If omitted, or if the image has mode "1" or "P", it is ##set to NEAREST. #e see also im.filter(filter) => image, which supports more filters. Maybe add it to our ops like flip & rotate? else: # new feature, bruce 061127, only works when width and height needn't shrink: # make new image, then use im.paste(image, box, [mask]) # "Image.new(mode, size) => image" img = self.img mode = img.mode #e or could alter this to convert it at the same time, says the doc size = (wd,ht) newimg = Image.new(mode, size) # "If the colour argument is omitted, the image is filled with black." # From the PIL docs: # "im.paste(image, box) pastes another image into this image. The box argument is either a 2-tuple # giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, # or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted image must match the size of the region. # If the modes don't match, the pasted image is converted to the mode of this image...." box = (0,0) # try this, even though I'm not sure upper left for PIL will be lower left for OpenGL, as I hope it will #k # in fact, it ends up drawn into the upper left... hmm... guess: tostring args 0, -1 are reversing it for OpenGL # (apparently confirmed by doc of PIL decoders); # so would I rather correct that here (move it to upper left), or when I get tex coords for drawing it?? ##e decide if 'A' in mode: ###k?? # experiment, bruce 061128: ##e might need to cause alpha of newimg to start out as 0 -- not sure what's done with it... we want to copy it # from what we paste, let it be 0 elsewhere. newimg.paste(img, box, img) # im.paste(image, box, mask) # motivation: doc says "Note that if you paste an "RGBA" image, the alpha band is ignored. # You can work around this by using the same image as both source image and mask." else: newimg.paste(img, box) ###k does this do some filtering too? visually it looks like it might have. Doc doesn't say it does. self.img = newimg try: self.update() # Note: an exception in self.update() will abort a current call of e.g. getTextureData, # but won't prevent the next call from working, since the modified image was already stored in self before this call. # That may mean it would make more sense to catch the exception here or inside update, complain, then discard it. # Doing that now. [bruce 061128] except: print_compact_traceback("bug: exception (ignored) in %r.update(): " % self) pass return def update(self): """ Update the image object. """ # Without saving/opening, 'tostring()' is not working right. # [bruce guess 061127 about the cause: maybe related to ops that don't # work before or after image is loaded. The docs mentioned elsewhere # are not very clear about this.] import os from platform_dependent.PlatformDependent import find_or_make_Nanorex_subdir nhdir = find_or_make_Nanorex_subdir("Nano-Hive") basename = os.path.basename(self.imageName) if self._tmpmode: # change file extension of tmp file to correspond with the format we'll store in it # [this is not needed (I think) except to not fool people who stumble upon the temporary file] basename, extjunk = os.path.splitext(basename) basename = "%s.%s" % (basename, self._tmpmode) newName = os.path.join(nhdir, 'temp_' + basename) ###e change file extension to one that always supports self.DESIRED_MODE? (or specify it in save command) oldmode = self.img.mode #bruce 061127 if self._tmpmode: self.img.save(newName, self._tmpmode) #bruce 061128 experimental, hopefully a temporary kluge else: self.img.save(newName) # if we use self.convert to convert PNG RGBA to RGBX, this can raise an exception: ## IOError: cannot write mode RGBX as PNG self.img = Image.open(newName) newmode = self.img.mode if oldmode != newmode and debug_flags.atom_debug and self.debug: #k does this ever happen?? print "debug warning: oldmode != newmode (%r != %r) in %r.update" % (oldmode, newmode, self) #e could set actual-size attrs here def flip(self): self.img = ImageOps.flip(self.img) self.update() def mirror(self): self.img = ImageOps.mirror(self.img) self.update() def rotate(self, deg): """ Rotate CCW <deg> degrees around center of the current image. """ self.img = self.img.rotate(deg) self.update() pass # end of class nEImageOps # end
NanoCAD-master
cad/src/graphics/images/ImageUtils.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ handles.py - graphical handles used in Extrude Mode. Deprecated for new code, since they don't use the Selobj_API used by most handle-like things. @author: Bruce @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. TODO: Needs cleanup. """ from Numeric import sqrt from geometry.VQT import V from geometry.VQT import vlen from geometry.VQT import norm from geometry.VQT import orthodist from graphics.drawing.CS_draw_primitives import drawsphere from utilities.constants import ave_colors from utilities.constants import magenta from utilities.constants import blue class handleWithHandleSet: """ used to wrap handles returned from a handleset, so they can use its methods """ def __init__(self, handle, handleset, copy_id = None): self.handle = handle self.handleset = handleset self.copy_id = copy_id def click(self): #e now leftDown, but later, "button press" leftUp self.handleset.click_handle( self.handle, self.copy_id) def move(self, motion): self.handleset.move_handle( self.handle, self.copy_id, motion ) def __repr__(self): return "handleWithHandleSet( %r, %r, %r)" % (self.handle, self.handleset, self.copy_id) def __str__(self): return self.handleset.str_handle( self.handle, self.copy_id) def leftDown_status_msg(self): return self.handleset.leftDown_status_msg( self.handle, self.copy_id) pass class HandleSet: """ maintain a set of spheres, able to be intersected with a ray, or a 3d point """ color = (0.5,0.5,0.5) # default color (gray50) radius_multiplier = 1.0 # this might be patched to some other value by our owner; # should affect all internal computations using radii, but not returned radii inside handle tuples ####NIM def __init__(self): self.origin = V(0,0,0) # changed from this only by certain subclasses, in practice self.handles = [] # list of (pos,radius,info) tuples # handlpos and maxradius are not used now, but might be used later to optimize this. self.handlpos = [] # list of their pos's (compare to singlpos in class Chunk (_recompute_singlpos)) self.maxradius = 0.01 # not true, but best if it's always positive, I think #e to optimize, we might want a "compile" method which caches Array versions of these lists def addHandle(self, pos, radius, info): """ add a handle of the given position, radius, and info, and return its index, unique in this Set """ self.handles.append((pos,radius,info)) self.handlpos.append(pos) if radius > self.maxradius: self.maxradius = radius return len(self.handles) # index of new handle #e needed? def compile(self): #e unused?? pass #e cache Array versions of some of our lists def move(self, offset): self.origin = self.origin + offset ## warning: this would be wrong (due to destructive mod of a vector): self.origin += motion def draw(self, glpane, offset = V(0,0,0), color = None, info = {}): # this code is copied/modified into a subclass, sorry """ draw our spheres (in practice we'll need to extend this for different sets...) """ ## self.radius_multiplier = 1.0 # this might be changed by certain subclass's process_optional_info method ## self.process_optional_info(info) # might reset instvars that affect following code... (kluge?) color = color or self.color ##detailLevel = 0 # just an icosahedron detailLevel = 1 # easier to click on this way ##radius = 0.33 # the one we store might be too large? no, i guess it's ok. #e (i might prefer an octahedron, or a miniature-convex-hull-of-extrude-unit) offset = offset + self.origin radius_multiplier = self.radius_multiplier color = tuple(color) + (1.0,) ## experiment 050218: alpha factor #bruce 051230 moved outside of loop to fix bug 1250 for (pos,radius,info) in self.handles: drawsphere(color, pos + offset, radius * radius_multiplier, detailLevel) ## def process_optional_info(self, info): ## "some subclasses should override this to let info affect draw method" ## pass def findHandles_containing(self, point): """ return a list of all the handles (in arbitrary order) which (as balls) contain the given 3d point """ res = [] for (pos,radius,info) in self.handles: #e revise this code if we cluster them, esp with bigger radius if vlen(point - pos) <= radius * self.radius_multiplier: res.append((pos,radius,info)) return res ## def findHandles_near(self, point, radius = None): ## """return a list (in arbitrary order) of pairs (dist, handle) for all the handles ## which are near the given point (within the given radius (default very large###e???), ## *or* within their own sphere-radius). #### WRONG CODE ## """ ## assert 0 def findHandles_exact(self, p1, p2, cutoff = 0.0, backs_ok = 1, offset = V(0,0,0)): """ @return: a list of (dist, handle) pairs, in arbitrary order, which includes, for each handle (spherical surface) hit by the ray from p1 thru p2, its front-surface intersection with the ray, unless that has dist < cutoff and backs_ok, in which case include its back-surface intersection (unless *that* has dist < cutoff). """ #e For now, just be simple, don't worry about speed. # Someday we can preprocess self.handlpos using Numeric functions, # like in nearSinglets and/or findSinglets # (I have untested prototype code for this in extrude-outs.py). hh = self.handles res = [] v = norm(p2-p1) # is this modifying the vector in-place, causing a bug?? ## offset += self.origin # treat our handles' pos as relative to this # I don't know, but one of the three instances of += was doing this!!! # probably i was resetting the atom or mol pos.... offset = offset + self.origin # treat our handles' pos as relative to this radius_multiplier = self.radius_multiplier for (pos,radius,info) in hh: ## bug in this? pos += offset pos = pos + offset radius *= radius_multiplier dist, wid = orthodist(p1, v, pos) if radius >= wid: # the ray hits the sphere delta = sqrt(radius*radius - wid*wid) front = dist - delta # depth from p1 of front surface of sphere, where it's hit if front >= cutoff: res.append((front,(pos,radius,info))) elif backs_ok: back = dist + delta if back >= cutoff: res.append((back,(pos,radius,info))) return res def frontDistHandle(self, p1, p2, cutoff = 0.0, backs_ok = 1, offset = V(0,0,0), copy_id = None): """ @return: None, or the frontmost (dist, handle) pair, as computed by findHandles_exact; but turn the handle into a pyobj for convenience of caller. """ # check: i don't know if retval needs self.radius_multiplier... # review: will we need to let caller know whether it was the front or # back surface we hit? or even the exact position on the sphere? if # so, add more data to the returned pair. dhdh = self.findHandles_exact(p1, p2, cutoff, backs_ok, offset = offset) if not dhdh: return None dhdh.sort() (dist, handle0) = dhdh[0] handle = self.wrap_handle(handle0, copy_id) return (dist, handle) def wrap_handle(self, handle, copy_id): (pos,radius,info) = handle # check format return handleWithHandleSet( handle, self, copy_id = copy_id) def click_handle( self, handle, copy_id): "click one of our own handles; subclasses should override this" pass def move_handle( self, handle, copy_id, motion): "move one of our own handles (e.g. when it's dragged); subclasses should override this" pass def str_handle( self, handle, copy_id): "subclasses are encouraged to override this so it looks good in messages to the user" (pos,radius,info) = handle return "<handle pos=%r, radius=%3f, info=%r, in copy %r of %r>" % (pos,radius,info,copy_id,self) def leftDown_status_msg( self, handle, copy_id): "subclasses should override this" return "" def handle_setpos( self, ind, newpos): "patch our arrays to change pos of just one handle" (pos,radius,info) = self.handles[ind] pos = newpos self.handles[ind] = (pos,radius,info) self.handlpos[ind] = pos #e might fail if we ever make self.compile() do something pass pass class draggableHandle_HandleSet(HandleSet): "a handleset, with behavior to let you drag the entire thing, and something else too" # used for "purple center"... def __init__(self, color = magenta, motion_callback = None, statusmsg = "draggable handle"): self.color = color self.motion_callback = motion_callback self.statusmsg = statusmsg HandleSet.__init__(self) def move_handle( self, handle, copy_id, motion): self.move(motion) if self.motion_callback: self.motion_callback(motion) return def leftDown_status_msg( self, handle, copy_id): return self.statusmsg pass class repunitHandleSet(HandleSet): #e this really belongs in extrudeMode.py, not in this file "a handleset for an extrudeable unit, which lets copy_id specify which repunit is meant" def __init__(self, *args, **kws): self.target = kws.pop('target') # must be specified; the extrudeMode object we're helping to control HandleSet.__init__(self, *args, **kws) def move_handle( self, handle, copy_id, motion): self.target.drag_repunit(copy_id, motion) def hset_name(self, copy_id): #e move this name code to the hset itself if copy_id: name = "repeat unit #%d" % copy_id else: name = "base unit" return name def str_handle( self, handle, copy_id): name = self.hset_name(copy_id) (pos,radius,info) = handle return "atom at pos=%r in %s" % (pos,name) def leftDown_status_msg( self, handle, copy_id): name = self.hset_name(copy_id) if copy_id: return "%s (can be dragged to change the offset)" % name else: return name # + " (can be dragged to move the entire model -- not implemented)" pass pass class niceoffsetsHandleSet(HandleSet): #e this really belongs in extrudeMode.py, not in this file "a handleset for holding the set of nice offsets" #e in future, we can show things on mouseover, perhaps like: # mouseover of nice_offset handle will light up its two singlets; # mouseover of a singlet will light up the applicable other singlets # and nice_offset handles; etc. special_pos = V(0,0,0) special_color = blue def __init__(self, *args, **kws): self.target = kws.pop('target') # must be specified; the extrudeMode object we're helping to control HandleSet.__init__(self, *args, **kws) def leftDown_status_msg( self, handle, copy_id): (pos,radius,info) = handle i1,i2 = info # this text is meant for the present situation, where we jump on mousedown; # better behavior would be buttonlike (jump on mouseup, iff still over handle), # and the text should be adjusted when we implement that #e return "overlapped bondpoints base#%d and rep#%d" % (i1,i2) def click_handle( self, handle, copy_id): self.target.click_nice_offset_handle(handle) ## def process_optional_info(self, info): ## bond_tolerance = info.get('bond_tolerance',1.0) ## self.radius_multiplier = bond_tolerance # affects draw() method def draw(self, glpane, offset = V(0,0,0), color = None, info = {}): # modified copy of superclass draw method "draw our spheres (in practice we'll need to extend this for different sets...)" ## self.radius_multiplier = 1.0 # this might be changed by certain subclass's process_optional_info method ## self.process_optional_info(info) # might reset instvars that affect following code... (kluge?) color = color or self.color ##detailLevel = 0 # just an icosahedron detailLevel = 1 # easier to click on this way ##radius = 0.33 # the one we store might be too large? no, i guess it's ok. #e (i might prefer an octahedron, or a miniature-convex-hull-of-extrude-unit) offset = offset + self.origin radius_multiplier = self.radius_multiplier special_pos = self.special_pos # patched in ###nim? special_pos = special_pos + offset #k?? or just self.origin?? special_color = self.special_color # default is used ## count = 0 for (pos,radius,info) in self.handles: radius *= radius_multiplier pos = pos + offset dist = vlen(special_pos - pos) if dist <= radius: color2 = ave_colors( 1.0 - dist/radius, special_color, color ) ## count += 1 else: color2 = color ## experiment 050218: add alpha factor to color color2 = tuple(color2) + (0.25,) drawsphere(color2, pos, radius, detailLevel) ## self.color2_count = count # kluge, probably not used since should equal nbonds return pass # we'll use the atoms of the mols # and a sep set or two # of special ones # and singlet-pair spheres (maybe variabe size) # ok to only use spheres for now # if the api could permit changing that # we don't want to force every stored handle to be an object! # .. # each handleset can compute, for one of its handles: # what to do on mouseover # change their color # give them a status message # (change cursor?) # what to do if you click, drag, mouseup (click - like button) (true button down/off/up behavior would be good) # what to do for a long drag # just these kinds for now: # rep unit atoms # base unit atoms # magenta # white # end
NanoCAD-master
cad/src/graphics/drawables/handles.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ ResizeHandle.py - provides Handles for resizing the parent object. The parent object in most cases is a reference geometry model object (e.g. Plane, Line etc) @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: Ninad 2007-10-16: Originally created and modified in Plane.py, while working on implemention of resizable Planes (in May-June 2007). Moved this class to its own module and renamed it to 'ResizeHandle' (the old name was 'Handle') """ from OpenGL.GL import glPushName from OpenGL.GL import glPopName from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GL import glTranslatef from OpenGL.GL import glRotatef from graphics.drawing.drawers import drawLineLoop from graphics.drawing.drawers import drawPlane import foundation.env as env from utilities.prefs_constants import selectionColor_prefs_key from utilities.constants import black, orange from math import pi from geometry.VQT import V from utilities.debug import print_compact_traceback from graphics.drawables.DragHandler import DragHandler_API from graphics.drawables.Selobj import Selobj_API ONE_RADIAN = 180.0 / pi # One radian = 57.29577951 degrees # This is for optimization since this computation occurs repeatedly # in very tight drawning loops. --Mark 2007-08-14 class ResizeHandle(DragHandler_API, Selobj_API): """ This class provides Handles for resizing the parent object. The parent object in most cases is a geometry (e.g. Plane, Line etc) @see: L{Plane._draw_handles} @Note: This is unrelated with the things in handles.py """ def __init__(self, parent, glpane, handleCenter): """ Constructor for class ResizeHandle @param parent: The parent object that can be resized using this handle. The parent can be a L{ReferenceGeometry} @param handleCenter: The center of the handle. If None, use the handle's I{center} property. @type handleCenter: L{V} or None """ self.parent = parent #this could be parent.glpane , but pass glpane object explicitely #for creating a handle to avoid any errors self.glpane = glpane self.center = handleCenter # No texture in handles (drawn ResizeHandle object). # Ideally the following value in the drawer.drawPlane method # should be False by default. self.textureReady = False self.pickCheckOnly = False ### REVIEW/TODO: understanding how self.pickCheckOnly might be # left over from one drawing call to another (potentially causing # bugs) is a mess. It needs to be refactored so that it's just an # argument to all methods it's passed through. This involves some # superclass methods; maybe they can be overridden so the argument # is only needed in local methods, I don't know. This is done in # several Node classes, so I added this comment to all of them. # (In this class, it looks like it's always False, but it's hard to # be sure re subclasses and superclasses.) # [bruce 090310 comment] self.glname = glpane.alloc_my_glselect_name(self) #bruce 080917 revised self.type = None def draw(self, hCenter = None): """ Public method to draw the resize handle. @param hCenter: The center of the handle. If None, use the handle's I{center} property. @type hCenter: L{V} or None @see: :{self._draw} which is called inside this method. """ try: glPushName(self.glname) if hCenter: self._draw(hCenter) else: self._draw() except: glPopName() print_compact_traceback( "ignoring exception when drawing handle %r: " % self) else: glPopName() def _draw(self, hCenter = None, highlighted = False): """ Draw the resize handle. It does the actual drawing work. @param hCenter: The center of the handle. If None, use the handle's I{center} property. @type hCenter: L{V} or None @param highlighted: This argument determines if the handle is drawn in the highlighted color. @type highlighted: bool @see: {self.draw} where this method is called. """ if hCenter: if self.center != hCenter: self.center = hCenter #Use glpane's scale for drawing the handle. This makes sure that # the handle is non-zoomable. side = self.glpane.scale * 0.018 glPushMatrix() #Translate to the center of the handle glTranslatef(self.center[0], self.center[1], self.center[2]) #Bruce suggested undoing the glpane.quat rotation and plane quat #rotation before drawing the handle geometry. -- ninad 20070525 parent_q = self.parent.quat if parent_q: glRotatef(-parent_q.angle * ONE_RADIAN, parent_q.x, parent_q.y, parent_q.z) glpane_q = self.glpane.quat glRotatef(-glpane_q.angle * ONE_RADIAN, glpane_q.x, glpane_q.y, glpane_q.z) drawPlane(env.prefs[selectionColor_prefs_key], side, side, self.textureReady, 0.9, SOLID = True, pickCheckOnly = self.pickCheckOnly) handle_hw = side/2.0 #handle's half width handle_hh = side/2.0 #handle's half height handle_corner = [V(-handle_hw, handle_hh, 0.0), V(-handle_hw, -handle_hh, 0.0), V( handle_hw, -handle_hh, 0.0), V( handle_hw, handle_hh, 0.0)] if highlighted: drawLineLoop(orange, handle_corner, width = 6) else: drawLineLoop( black, handle_corner, width = 2) glPopMatrix() def draw_in_abs_coords(self, glpane, color): """ Draw the handle as a highlighted object. @param glpane: The 3D Graphics area. @type gplane: L{GLPane} @param color: Unused. @type color: @attention: I{color} is not used. """ q = self.parent.quat glPushMatrix() if self.parent.center: glTranslatef( self.parent.center[0], self.parent.center[1], self.parent.center[2]) if q: glRotatef( q.angle * ONE_RADIAN, q.x, q.y, q.z) self._draw(highlighted = True) glPopMatrix() def move(self, offset): """ Move the handle by I{offset}. @param offset: The offset of the handle, in Angstroms. @type offset: V """ self.center += offset def setType(self, handleType): """ Sets the handle type. @param handleType: The handle type. Must be one of: 'Width-Handle', 'Height-Handle','Corner' or just '' (type not specified) @type handleType: str """ assert handleType in [ 'Width-Handle', 'Height-Handle', 'Corner', ''] self.type = handleType def getType(self): """ Returns the handle type. @return: The handle type, which is either 'Width-Handle', 'Height-Handle', or 'Corner'. @rtype: str """ assert self.type is not None return self.type ###============== selobj interface Starts ===============### #Methods for selobj interface . Note that draw_in_abs_coords method is #already defined above. -- Ninad 20070612 #@TODO Need some documentation. Basically it implements the selobj #interface mentioned in exprs.Highlightable.py def leftClick(self, point, event, mode): mode.handleLeftDown(self, event) mode.update_selobj(event) return self def mouseover_statusbar_message(self): msg1 = "Parent:" msg2 = str(self.parent.name) type = self.getType() if type: msg3 = " Type: " else: msg3 = '' msg4 = type return msg1 + msg2 + msg3 + msg4 def highlight_color_for_modkeys(self, modkeys): return orange # Copied Bruce's code from class Highlightable with some mods. # Need to see if selobj_still_ok() is needed. OK for now. # --Ninad 2007-05-31 def selobj_still_ok(self, glpane): # bugfix: compare to correct class [bruce 070924] res = self.__class__ is ResizeHandle if res: our_selobj = self glname = self.glname owner = glpane.assy.object_for_glselect_name(glname) if owner is not our_selobj: res = False # Do debug prints. print "%r no longer owns glname %r, instead %r does" \ % (self, glname, owner) #[perhaps never seen as of 061121] pass if not res and env.debug(): print "debug: selobj_still_ok is false for %r" % self return res ###============== selobj interface Ends ===============### ###=========== Drag Handler interface Starts =============### #@TODO Need some documentation. Basically it implements the drag handler #interface described in DragHandler.py See also exprs.Highlightable.py def handles_updates(self): return True def DraggedOn(self, event, mode): mode.handleLeftDrag(self, event) mode.update_selobj(event) return def ReleasedOn(self, selobj, event, mode): pass ###=========== Drag Handler interface Ends =============###
NanoCAD-master
cad/src/graphics/drawables/ResizeHandle.py
# Copyright 2006-2009 Nanorex, Inc. See LICENSE file for details. """ Selobj.py -- provides class Selobj_API, [### WHICH WILL BE RENAMED, ALONG WITH THIS FILE] which documents the interface from the GLPane to drawable objects which need to detect whether the mouse touches them, i.e. mainly for "hover-highlightable" objects, and from other code to whatever such objects are stored in glpane.selobj (since they are actually under the mouse). @author: Bruce @version: $Id$ @copyright: 2006-2009 Nanorex, Inc. See LICENSE file for details. Current status [bruce 080116]: This partly formalizes an informal API used by GLPane and some Commands and GraphicsModes to handle hover-highlightable drawable objects, which has optional methods for some optional abilities they can have, like a different highlight appearance, an ability to provide a context menu, or an ability to provide a DragHandler. There is unfortunately not yet a single consistent API for "drawables" in NE1. For example, many classes have draw or Draw methods, but these can have two or three different arg signatures in different class hierarchies. The Selobj_API is not a general "drawable API" but covers most ways in which a drawable object might interact with the mouse. As currently constructed it's unideal in several ways, e.g. its methods have no consistent naming convention, and the semantics for "using the default behavior" is often "don't provide the method", which means we can't provide a default or stub implementation in class Selobj_API itself (effectively an "interface class") or we'd break code. And, in reality it's probably at least two APIs mushed together. And certainly it's unclearly named. The confusion apparent in the docstring and comments of Selobj.py (class Selobj_API) reflects all this. This can and should all be cleaned up, but we're unlikely to do much of that before FNANO '08. In the meantime, making the classes that provide the existing "selobj interface" say they do so is at least a start, since the set of things to look at to understand all this is more clearly defined. To clarify: this commit [080116] does not change any behavior or rename any methods. It only adds an empty superclass to all existing classes which use methods from the preexisting informal "selobj interface", thereby partially formalizing the interface. (It formalizes which classes provide it, though with no detection of errors in this, but it does not formalize what methods are part of it -- the comments in Selobj.py are the most we have in that direction.) === ### REVIEW: is that really two different interfaces? The GLPane, finding the selobj via glname, could ask it to return the value to actually store in glpane.selobj. First interface is " an object (drawable) which notices the mouse over it", second is "an object which handles events for the object under the mouse"... they might not be in 1-1 correspondence when we have good support for nested glnames! sort of like a mouse-sensitive drawable vs a mouse-handling model object... or a mouse event handler for a model object... or for a drawable (or a nested chain of them, depending on glname nesting for e.g. stereo, or repeated identical parts) Note: a drag-handler (see DragHandler.py) and a "selobj" are often the same object, but obeying a different API; drag_handlers are return values from a Selobj_API-interface method (which often returns self). Implementation note: in the current code, all such objects ask the GLPane (actually the global env module, but ideally a GL Context representative) to allocate them a "glname" for use during GL_SELECT drawing, but this implementation may change or be augmented, both for efficiency and to work for transparent objects. Note: most objects which implement this interface don't currently [070913] inherit class Selobj_API. Since the methods in it needn't be overridden, most client code tests for their presence, and in some cases runs non-noop default code if they are not found. This should be revised so that all implementors inherit this class, and so that the default code is moved to default methods in this class. WARNING: Until that revision is done, adding this superclass to existing objects would break code in the GLPane or in modes, which relies on testing for the lack of presence of certain methods in this API to decide when to run its own default code instead of calling those methods. Or at least it would if this class had any methods defined in it ... maybe we should leave the methods out, add the superclass, then move the methods and their client-supplied default code into this class gradually. The init code which allocates a glname should also be moved into an init method in this class. Current classes which should inherit this interface include Atom, Bond, Jig, and Highlightable, and others which have comments about "selobj interface", e.g. in Plane and DirectionArrow modules. All comments about either "selobj interface" or "Drawable API" may relate to this and should be revised. See also scratch/Drawable.py. Some documentation about this interface exists in exprs/Highlightable.py and GLPane.py. Module classification: Seems most like graphics_behavior_api, but revisit when it's done. [bruce 071215] """ # possible names for this class: # - class MouseSensor_interface (in file MouseSensor.py? or MouseSensor_interface.py?) # - class MouseSensitive -- maybe that grammar (adjective) means _interface can be # implied? not sure. # And should the methods start with a prefix like MouseSensor_ ? class Selobj_API: """ ###doc WARNING: API details (method names, arglists) are subject to change. """ ### see list of methods below -- but don't add any method stubs here # for now, or some code will break (as explained in module docstring). # some *new* api methods and attrs can safely be added here: _selobj_colorsorter_safe = False #bruce 090311 def nodes_containing_selobj(self): #bruce 080507 """ Return a list (not a tuple) of all nodes that contain self, in innermost-to-outermost order if convenient. If self bridges multiple leaf nodes (e.g. if self is an external bond), include all those leaf nodes (and all their containing nodes) in the result, but in that case, the order of nodes within the result is undefined, and whether the result might contain some nodes twice is undefined. """ return [] pass # comment moved from exprs/Highlightable.py, edited here : # == selobj interface ###e should define a class for the selobj interface; see classes Highlightable and # _UNKNOWN_SELOBJ_class for an example -- # methods desired by glpane for analyzing hits, responding to them # - object.glname (?) # [note, not really a public attribute; e.g. class Atom made it private # and introduced get_glname method on 080220] # - and the env table for glname to object -- in future that goes to first kind of obj, # it returns 2nd kind [note: being moved from env to assy as of bruce 080220] # (and does glpane need to remember more than just one selobj it returns??) # and by mode for passing on events: # - leftClick # - make_selobj_cmenu_items # by glpane for drawing selobj -- not sure how to classify these -- but only done on one # object so i think it's on the 2nd interface # - selobj_still_ok, [glpane asks mode(?), default implem asks selobj] # - draw_in_abs_coords, # - highlight_color_for_modkeys # - mouseover_statusbar_message (used in GLPane.set_selobj) # other things looked at on a selobj: # - getInformationString (maybe not on all objects??) # - killed # - glname (might be a kluge) # - part (only on some kinds?) # see also: _UNKNOWN_SELOBJ_class # new, 070919 - here are the distinct interfaces... """ gl select hit detector - for an object with a glname, which draws inside it - must draw in a special way related opengl names: glSelectBuffer, glselect/glname in our own related internal names, glRenderMode(GL_SELECT) class GL_SELECT_HitDetector_Mixin (other kinds of hit detectors - they'd need geometric info in api, but would not need to draw at all, let alone specially -- except insofar as to record unambiguously when they did get drawn, ie whether they are really in the scene, and if so under what coordsys that was (when in display lists). maybe "draw" means "add self to that frame scene tree"?? or maybe we imitate glselect and repeat the draw in a special way? as my partly done expr draw reform was trying to do, for its own hit detection to work inside display lists...) == ObjectUnderMouse_interface - for anything which can be returned as the object under the mouse, then queried about what to do, or even about how to draw itself specially (over its ordinary representation, which may have to be drawn too, being in a display list). glpane.selobj rename to glpane.objectUnderMouse (someday) selobj - an object assignable to glpane.selobj - should provide actions in ui for mouse events over it - highlightable, draggable, ... mouse sensitive - handler of mouse events - can ask for this obj under mouse - == Q: is being overdrawn specially, a different interface than being objectUnderMouse? evidence: objUnderMouse might say "here are the objects to overdraw specially" and they might be more than just it. It would call all their drawing code with special flags (look highlighted in certain way) and in abs coords... latter might be fixed if we reimplemented how this works as a separate drawing pass, someday. but note that in current code this object also gets first dibs at providing the next detected hit using stencil buffer... hmm... what does stencil buffer say about how all these interfaces have to be related? ### Can I factor out the related code from the GLPane, while I'm doing this? And fix some bugs and add required new APIs at same time (fix bugs in highlightable vs displists, add api for region sel, and for multiple highlighted objects for single obj under mouse) == region selection interface - a node which contains region-selectable things and control points for them """ ### REVIEW: should check_target_depth_fudge_factor # be an attribute of each object which can be drawn as selobj, instead of an attr of the mode? # (as of 070921 it's an optional mode attr, default value supplied by its client, GLPane.) # outtake?? ####@@@@ TODO -- rename draw_in_abs_coords and make it imply highlighting so obj knows whether to get bigger # (note: having it always draw selatoms bigger, as if highlighted, as it does now, would probably be ok in hit-test, # since false positives in hit test are ok, but this is not used in hit test; and it's probably wrong in depth-test # of glselect_dict objs (where it *is* used), resulting in "premonition of bigger size" when hit test passed... ###bug); # make provisions elsewhere for objs "stuck as selobj" even if tests to retain that from stencil are not done # (and as optim, turn off stencil drawing then if you think it probably won't be needed after last draw you'll do) # end
NanoCAD-master
cad/src/graphics/drawables/Selobj.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ DirectionArrow.py @author: Ninad @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. History: ninad 2007-06-12: Created this class (initially) to support the implementation of 'offset plane' (was created in Plane.py) ninad 2007-08-20: Split it out of Plane.py into this new file. TODO: - Need to implement some grid plane features. - Plane should be selectable when clicked anywhere inside. """ from OpenGL.GL import glPushName from OpenGL.GL import glPopName from OpenGL.GL import glPushMatrix from OpenGL.GL import glTranslatef from OpenGL.GL import glRotatef from OpenGL.GL import glPopMatrix from graphics.drawing.CS_draw_primitives import drawDirectionArrow from geometry.VQT import V, norm, vlen from math import pi from utilities.constants import gray, orange from utilities.debug import print_compact_traceback from graphics.drawables.DragHandler import DragHandler_API from graphics.drawables.Selobj import Selobj_API import foundation.env as env ONE_RADIAN = 180.0 / pi # One radian = 57.29577951 degrees # This is for optimization since this computation occurs repeatedly # in very tight drawning loops. --Mark 2007-08-14 class DirectionArrow(DragHandler_API, Selobj_API): """ The DirectionArrow class provides a 3D direction arrow that can be interacted with in the 3D graphics area. The direction arrow object is created in its parent class. (class corresponding to self.parent) Example: Used to generate a plane offset to the selected plane, in the direction indicated by the direction arrow. Clicking on the arrow reverses its direction and thus the direction of the plane placement. """ def __init__(self, parent, glpane, tailPoint, defaultDirection): """ Creates a direction arrow. @param parent: The parent object. @type parent: @param glpane: The 3D graphics area object. @type glpane: L{GLPane} @param tailPoint: The origin of the arrow. @type tailPoint: V @param defaultDirection: The direction of the arrow. @type defaultDirection: """ self.parent = parent self.glpane = glpane self.tailPoint = tailPoint self.direction = defaultDirection self.glname = glpane.alloc_my_glselect_name(self) #bruce 080917 revised self.flipDirection = False self.drawRequested = False def setDrawRequested(self, bool_request = False): """ Sets the draw request for drawing the direction arrow. This class's draw method is called in the parent class's draw method This functions sets the flag that decides whether to draw direction arrow (the flag value is returned using isDrawRequested method. @param bool_request: Default is False. (request to draw direction arrow) @type bool_request: bool """ self.drawRequested = bool_request def isDrawRequested(self): """ Returns the flag that decides whether to draw the direction arrow. @return B{self.drawRequested} (boolean value) @rtype instance variable B{self.drawRequested} """ return self.drawRequested def draw(self): """ Draw the direction arrow. (This method is called inside of the parent object's drawing code. """ try: glPushName(self.glname) if self.flipDirection: self._draw(flipDirection = self.flipDirection) else: self._draw() except: glPopName() print_compact_traceback("ignoring exception when drawing handle %r: " % self) else: glPopName() pass def _draw(self, flipDirection = False, highlighted = False): """ Main drawing code. @param flipDirection: This flag decides the direction in which the arrow is drawn. This value is set in the leftClick method. The default value is 'False' @type flipDirection: bool @param highlighted: Decids the color of the arrow based on whether it is highlighted. The default value is 'False' @type highlighted: bool """ if highlighted: color = orange else: color = gray if flipDirection: #@NOTE: Remember we are drawing the arrow inside of the _draw_geometry #so its drawing it in the translated coordinate system (translated #at the center of the Plane. So we should do the following. #(i.e. use V(0,0,1)). This will change if we decide to draw the #direction arrow outside of the parent object #requesting this drawing.--ninad 20070612 #Using headPoint = self.tailPoint + V(0,0,1) * 2.0 etc along with #the transformation matrix in self.draw_in_abs_coordinate() #fixes bug 2702 and 2703 -- Ninad 2008-06-11 headPoint = self.tailPoint + V(0,0,1) * 2.0 ##headPoint = self.tailPoint + 2.0 * norm(self.parent.getaxis()) else: headPoint = self.tailPoint - V(0,0,1) * 2.0 ##headPoint = self.tailPoint - 2.0 * self.parent.getaxis() vec = vlen(headPoint - self.tailPoint) vec = self.glpane.scale*0.07*vec tailRadius = vlen(vec)*0.16 drawDirectionArrow(color, self.tailPoint, headPoint, tailRadius, self.glpane.scale, flipDirection = flipDirection) def draw_in_abs_coords(self, glpane, color): """ Draw the handle as a highlighted object. @param glpane: B{GLPane} object @type glpane: L{GLPane} @param color: Highlight color """ q = self.parent.quat glPushMatrix() glTranslatef( self.parent.center[0], self.parent.center[1], self.parent.center[2]) glRotatef( q.angle * ONE_RADIAN, q.x, q.y, q.z) if self.flipDirection: self._draw(flipDirection = self.flipDirection, highlighted = True) else: self._draw(highlighted = True) glPopMatrix() ###=========== Drag Handler interface Starts =============### #@TODO Need some documentation. Basically it implements the drag handler #interface described in DragHandler.py See also exprs.Highlightable.py # -- ninad 20070612 def handles_updates(self): return True def DraggedOn(self, event, mode): return def ReleasedOn(self, selobj, event, mode): pass # =========== Drag Handler interface Ends ============= # ============== selobj interface Starts ============== #@TODO Need some documentation. Basically it implements the selobj # interface mentioned in exprs.Highlightable.py -- ninad 2007-06-12 def leftClick(self, point, event, mode): """ Left clicking on the DirectionArrow flips its direction. @param point: not used for now. @type point: V @param event: Left down event. @type event: QEvent @param mode: Current mode program is in. @type mode: L{anyMode} """ self.flipDirection = not self.flipDirection mode.update_selobj(event) mode.o.gl_update() return self def mouseover_statusbar_message(self): """ Returns the statusbar message to display when the cursor is over the direction arrow in the 3D graphics area. @return: The statusbar message @rtype: str """ msg1 = "Click on arrow to flip its direction" return msg1 def highlight_color_for_modkeys(self, modkeys): return orange # Copied Bruce's code from class Highlightable with some mods. # Need to see if selobj_still_ok() is needed. OK for now. # --Ninad 2007-05-31 def selobj_still_ok(self, glpane): res = self.__class__ is DirectionArrow if res: our_selobj = self glname = self.glname owner = glpane.assy.object_for_glselect_name(glname) if owner is not our_selobj: res = False # Do debug prints. print "%r no longer owns glname %r, instead %r does" \ % (self, glname, owner) # [perhaps never seen as of 061121] pass pass if not res and env.debug(): print "debug: selobj_still_ok is false for %r" % self return res ###============== selobj interface Ends===============### pass
NanoCAD-master
cad/src/graphics/drawables/DirectionArrow.py
NanoCAD-master
cad/src/graphics/drawables/__init__.py
# Copyright 2008 Nanorex, Inc. See LICENSE file for details. """ @author: Ninad @copyright: 2008 Nanorex, Inc. See LICENSE file for details. @version: $Id$ @license: GPL TODO: To be revised. This handle can't be dragged. (need modifications in DragBehavior_AlongCircle). Also the handle appearance needs to be changed. """ from exprs.attr_decl_macros import Option from exprs.attr_decl_macros import State from exprs.Set import Action from exprs.__Symbols__ import _self from exprs.Overlay import Overlay from exprs.ExprsConstants import Drawable from exprs.ExprsConstants import Color from exprs.ExprsConstants import ORIGIN, DX , DY from exprs.dna_ribbon_view import Cylinder from exprs.Rect import Sphere import foundation.env as env from utilities.prefs_constants import hoverHighlightingColor_prefs_key from utilities.prefs_constants import selectionColor_prefs_key from utilities.constants import white, purple from geometry.VQT import V from exprs.DraggableHandle_AlongCircle import DraggableHandle_AlongCircle #Use this flag to test some 'fancy handle drawings' (the default apaprearance is #'sphere' DEBUG_FANCY_HANDLES = True class RotationHandle(DraggableHandle_AlongCircle): """ Provides a resize handle for editing the length of an existing DnaSegment. """ #Handle color will be changed depending on whether the the handle is grabbed #So this is a 'State variable and its value is used in 'appearance' #(given as an optional argument to 'Sphere') handleColor = State( Color, purple) if DEBUG_FANCY_HANDLES: appearance = Overlay( Sphere(1.2, handleColor, center = ORIGIN + _self.axis*3*DX), Cylinder((ORIGIN, ORIGIN + _self.axis*2*DX), 0.5 ,handleColor)) HHColor = env.prefs[hoverHighlightingColor_prefs_key] appearance_highlighted = Option( Drawable, Overlay( Sphere(1.2, HHColor, center = ORIGIN + _self.axis*3*DX), Cylinder((ORIGIN, ORIGIN + _self.axis*2*DX), 0.5 , HHColor)), doc = "handle appearance when highlighted") else: #Appearance of the handle. (note that it uses all the code from exprs module # and needs more documentation there). #See exprs.Rect.Sphere for definition of a drawable 'Sphere' object. appearance1 = Option( Drawable, Sphere(1.2, handleColor), doc = "handle appearance when not highlighted") #Handle appearance when highlighted appearance_highlighted1 = Option( Drawable, Sphere(1.2, yellow), doc = "handle appearance when highlighted") #Stateusbar text. Variable needs to be renamed in superclass. sbar_text = Option(str, "Drag the handle to rotate the segment around axis", doc = "Statusbar text on mouseover") #Command object specified as an 'Option' during instantiation of the class #see DnaSegment_EditCommand class definition. command = Option(Action, doc = 'The Command which instantiates this handle') def on_press(self): """ Actions when handle is pressed (grabbed, during leftDown event) @see: B{SelectChunks.GraphicsMode.leftDown} @see: B{DnaSegment_EditCommand.grabbedHandle} @see: B{DnaSegment_GraphicsMode.Draw} (which uses some attributes of the current grabbed handle of the command. @see: B{DragHandle_API} """ #Change the handle color when handle is grabbed. See declaration of #self.handleColor in the class definition. self.handleColor = env.prefs[selectionColor_prefs_key] #assign 'self' as the curent grabbed handle of the command. self.command.grabbedHandle = self def on_drag(self): """ Method called while dragging this handle . @see: B{DragHandle_API} """ #Does nothing at the moment. pass def on_release(self): """ This method gets called during leftUp (when the handle is released) @see: B{DnaSegment_EditCommand.modifyStructure} @see: self.on_press @see: B{SelectChunks.GraphicsMode.leftUp} @see: B{DragHandle_API} """ self.handleColor = purple if self.command: #Clear the grabbed handle attribute (the handle is no longer #grabbed) self.command.grabbedHandle = None
NanoCAD-master
cad/src/graphics/drawables/RotationHandle.py
# Copyright 2006-2008 Nanorex, Inc. See LICENSE file for details. """ DragHandler.py -- provides class DragHandler_API, which documents the interface from selectMode to highlightable objects which want to handle their own mouse events (unlike Atom, Bond, and Jig, whose behavior is hardcoded into selectMode), and possibly provides default implementations or useful helper methods. @author: Bruce @version: $Id$ @copyright: 2006-2008 Nanorex, Inc. See LICENSE file for details. REVIEW: should it be renamed to DragHandler, or to DragHandler_interface, or to something else? """ class DragHandler_API: """ Document the drag_handler interface (implemented by selectMode and its subclasses), and provide default implems for its methods. [### need an overview and more details here] WARNING: API details (method names, arglists) are subject to change. """ # example subclasses: class Highlightable in exprs.Highlightable; some in cad/src # Q: how does this relate to the selobj interface? # (Note: the "selobj interface" is an informal interface implemented by GLPane.py # for hover-highlightable objects. It has some documentation in exprs/Highlightable.py and GLPane.py.) # A: a drag-handler and selobj are often the same object, but obeying a different API; # drag_handlers are retvals from a selobj-interface method (which typically returns self). def handles_updates(self): """ Return True if you will do MT and glpane updates as needed, False if you want client mode to guess when to do them for you. (It will probably guess: do both, on mouse down, drag, up; but do neither, on baremotion == move, except when selobj changes.) """ return False # otherwise subclass is likely to forget to do them def DraggedOn(self, event, mode): pass def ReleasedOn(self, selobj, event, mode): pass def leftDouble(self, event, mode):#070324 added this method to the interface (note: the call is implemented only in testmode) pass pass # end
NanoCAD-master
cad/src/graphics/drawables/DragHandler.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ special_drawing.py - help class ChunkDrawer do special drawing in extra display lists @author: Bruce @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. TODO: Eventually, this should be divided into general and specific modules, with some parts refiled into foundations. """ from graphics.drawing.ColorSorter import ColorSorter from graphics.drawing.ColorSortedDisplayList import ColorSortedDisplayList from utilities.Comparison import same_vals import foundation.env as env from foundation.changes import SubUsageTrackingMixin from utilities.debug import print_compact_traceback from utilities import debug_flags DEBUG_COMPARATOR = False # == class _USE_CURRENT_class(object): """ ###TODO: doc """ def __getitem__(self, key): # get the "current glpane" and its graphicsMode # (for purposes of determining modes & prefs) # (how we do it is not necessarily a kluge, given that this is being # used to define a constant value for use when a better one was # not passed) if debug_flags.atom_debug: print "fyi: getting %r from %r" % (key, self) # This happens 5 or 6 times when entering Build Atoms command; # not sure why, but probably ok. # Historical note: On 081003 I fixed what I thought was a typo below # (mainWindow -> mainwindow), here and in another place below, # and was surprised that this had no effect, and wondered why the # prior presumed exception had been silently discarded. In fact, # it was not a typo -- mainWindow is an alias for mainwindow in env. # So there was no exception and there is no mystery. # (An actual exception here causes, at least, a bug when hovering # over a 3' strand end arrowhead, in Select Chunks mode.) # [bruce 081211 comment] win = env.mainwindow() glpane = win.glpane graphicsMode = glpane.graphicsMode # let the graphicsMode interpret the prefs key, # in case it wants to override it with a local pref # (or conceivably, someday, track it in a different way) # (note, ThumbView has no graphicsMode, but that doesn't # affect this code since it uses main glpane even when # drawing into a ThumbView. [bruce 080606 comment]) try: res = graphicsMode.get_prefs_value(key) except: msg = "bug: exception in %r.get_prefs_value(%r), %s" % \ (graphicsMode, key, "falling back to env.prefs") print_compact_traceback(msg + ": ") res = env.prefs[key] return res pass USE_CURRENT = _USE_CURRENT_class() ### TODO: doc # == # kinds of special drawing (only one so far) SPECIAL_DRAWING_STRAND_END = 'SPECIAL_DRAWING_STRAND_END' ALL_SPECIAL_DRAWING_KINDS = [SPECIAL_DRAWING_STRAND_END] # === # usage tracking functions # # when the dust settles, the general class here # should be moved into foundation (it's related to changes.py), # and the specific one into a module for the strand-end-specific # part of this, unless it turns out to be more general than that # (applying potentially to all prefs values). class UsedValueTrackerAndComparator(object): """ Abstract class. Subclasses must define method _compute_current_value, which computes the current value associated with some sort of key, e.g. a prefs key. They must also have "recomputation code" which calls self.get_value as described below. ### REVIEW whether this later guess is correct: It is *not* necessary for _compute_current_value to do "standard usage tracking" of the kind defined in changes.py. This class is not directly related to that facility. However, clients may want it to do that for their own purposes, to track usage into the context in which they're called. NOTE THAT WE CACHE VALUES and this will defeat that tracking unless client code calls self.invalidate whenever they might have changed. ### Client code will have an instance of this class for each recomputation it wants to track separately for the need to be redone. When the client wants to use the result of the computation and is worried it might not be current, it calls self.do_we_need_to_recompute(), which checks whether self.invalidate() has been called, and if not, whether all keys that were used (i.e. passed to self.get_value) last time it recomputed still have the same value (according to same_vals). If that's false, our client can safely use its cached result from the last time it recomputed. But if that's true, the client calls self.before_recompute(), then does the computation and records the result (independently of this object except for calls to self.get_value which the client does during its recomputation), then calls self.after_recompute(). """ _recomputing = False valid = False # whether client's recomputation is up to date, # as far as we know. Client should use this as *its* valid flag # and invalidate it as needed by calling self.invalidate(). def __init__(self): # since not valid, no need to _reset return # == Methods to use during a recomputation by the client # (or during a side effect treated as recomputation, such as drawing, # where "whatever gets drawn" has the role of the computation output) def before_recompute(self): #e rename? """ Prepare for the client to do another recomputation which will call self.get_value for all keys whose values we need to track usage of. See class docstring for more info. """ assert not self._recomputing self._ordered_key_val_pairs = [] # in order of usage # note: order can matter, if some keys' values are not safe # to access for comparison unless others before them # still have the same values self._keys_used = {} # maps key -> val, but unordered self.valid = False self._recomputing = True return def get_value(self, key, context): """ ... call this while redoing the client computation... ... it passes context along to self._compute_current_value ... It will record the value it returns, both to optimize repeated calls, and so it can be compared to the new current value by self.do_we_need_to_recompute() when the client next considers doing a recomputation. """ # usage note: current code calls this (indirectly) in place of env.prefs # when drawing extra displist contents if not self._keys_used.has_key(key): val = self._compute_current_value(key, context) # review [081223]: should we track usage by that in changes.py manner, # into self.invalidate? NO! instead, either we or certain clients # ought to discard tracked usage from this! they can do that # since all worries about changes are taken care of by # our recording the value and comparing it. # (assuming, if side effects matter, they are uniquely # labeled by the recorded value, e.g. it's a change_indicator # or change_counter). # Guess: in current client code special_drawing) this is not done, # and it causes some unnecessary invals here, at least in principle. # inline our implementation of self._track_use self._keys_used[key] = val self._ordered_key_val_pairs += [(key, val)] else: val = self._keys_used[key] return val def _compute_current_value(self, key, context): assert 0, "subclass must implement %r%s %r" % \ (self, "._compute_current_value for key", key) pass def _track_use(self, key, val): """ """ # safe public version, ok to call more than once for same key; # inlined by get_value; # REVIEW: perhaps this has no direct calls and can be removed? # NOTE: not directly related to env.track_use or the associated # usage tracking system in changes.py. if not self._keys_used.has_key(key): self._keys_used[key] = val self._ordered_key_val_pairs += [(key, val)] return def after_recompute(self): """ Must be called by the client after it finishes its recomputation. See class docstring for more info. """ assert self._recomputing del self._recomputing self.valid = True return # == methods to use between computations by the client def invalidate(self): """ Client realizes its recomputation is invalid for "external reasons". """ if self.valid: self.valid = False # and that means these attrs won't be needed ... del self._keys_used del self._ordered_key_val_pairs return # == methods to use when client is deciding whether to do a # recomputation or reuse a cached value def do_we_need_to_recompute(self, context): """ Assume the client is in a context in which it *could* safely/correctly recompute, in terms of _compute_current_value being safe to call and returning the correct value for whatever keys a recomputation would pass to it (when passed the given context parameter). @return: whether the client needs to do its recomputation (True) or can reuse the result it got last time (and presumably cached) (False) See class docstring for more info. """ assert not self._recomputing if not self.valid: # the code below would be wrong in this case return True for key, val in self.ordered_key_val_pairs(): # Note: doesn't call self._track_use, which would be a noop. ###todo: clarify newval = self._compute_current_value(key, context) if not same_vals(val, newval): #e Could optim the test for specific keys; probably not worth it # though. ###TODO: OPTIM: Could optim self.before_recompute # (for some callers -- REVIEW, which ones exactly?) # to leave the values cached that were already found to be # the same (by prior iterations of this loop). # We'd do this by deleting the different values here # (and the not yet compared ones); # this would make the following note partly incorrect. # Note: We don't call self.invalidate() here, in case client # does nothing, current state changes, and it turns out we're # valid again. Clients doubting this matters, and which are not # going to recompute right away, and which want to optimize # repeated calls of this (by avoiding redoing the same_vals # tests) can call self.invalidate themselves. Most clients # needn't bother since they'll recompute right away. return True return False def ordered_key_val_pairs(self): """ @return: a list of zero of more (key, val) pairs that were used by our client computation the last time it ran. @warning: caller must not modify the list we return. """ return self._ordered_key_val_pairs pass # end of class UsedValueTrackerAndComparator # == class SpecialDrawing_UsedValueTrackerAndComparator( UsedValueTrackerAndComparator): """ ... if necessary, reset and re-track the values used this time... knows how to compute them... @note: this computes the same results as USE_CURRENT, but unlike it, does tracking with UsedValueTrackerAndComparator. """ def __init__(self): UsedValueTrackerAndComparator.__init__(self) return def _compute_current_value(self, key, context): """ Compute current value for key in context when needed by self.get_value implemented in superclass (which happens when superclass code has no cached value for this key in self). In this subclass, that value for key is computed by treating context as a GraphicsMode and calling its get_prefs_value method. """ ## print "compute current value:", key, context # require key to be in a hardcoded list?? graphicsMode = context return graphicsMode.get_prefs_value(key) # see also USE_CURRENT def __getitem__(self, key): # KLUGE 1: provide this interface in this class # rather than in a wrapper class. (No harm, AFAIK, but only # because prefs key strings don't overlap any of our # public or private method or attribute names.) # KLUGE 2: get current global graphicsMode # instead of getting it from how we're called. # (See also USE_CURRENT, which also does this, # but in its case it's not a kluge.) ### TODO to fix this kluge: make a "prefs value object" which # wraps this object but stores glpane, to use instead of this object. # But note that this would not work with glpane == a ThumbView # since ThumbView has no graphicsMode attribute! So we'd have to # wrap the "env-providing glpane" instead, i.e. the main one # for any ThumbView in current code. if debug_flags.atom_debug: print "fyi: getting %r from %r" % (key, self) # This happens a lot in Break Strands command, as expected. # See also the historical note about similar code above -- # I mistakenly thought this code had an exception, but it didn't. # (An actual exception here causes Break Strands to not display # strand-ending Ss atoms at all.) # [bruce 081211 comment] win = env.mainwindow() glpane = win.glpane graphicsMode = glpane.graphicsMode context = graphicsMode return self.get_value(key, context) pass # === class ExtraChunkDisplayList(object, SubUsageTrackingMixin): """ Abstract class. Subclass must define method _construct_args_for_drawing_functions. Has a public member, self.csdl, whose value is a ColorSortedDisplayList used for doing some kind of extra drawing associated with a ChunkDrawer, but not drawn as part of its main CSDL. Also holds the state that determines whether self.csdl is invalid, and under what conditions it will remain valid. Helps figure out when to invalidate it, redraw it, etc. External code can call self.csdl.draw(), but only when it knows that self.csdl is already valid. This probably means, only when highlighting self after it's already been drawn during the same frame. @note: there is a cooperating object Chunk_SpecialDrawingHandler which knows about storing our instances in a ChunkDrawer.extra_displists attribute, but this class itself (or its subclass, so far) knows nothing about where they are stored. """ # class constants # Subclass must override, with a subclass of UsedValueTrackerAndComparator. _comparator_class = None # default values of instance variables ## valid = False -- WRONG, we use self.comparator.valid for this. def __init__(self, transformControl = None): self.csdl = ColorSortedDisplayList(transformControl) # self.csdl is a public attribute, see class docstring self.comparator = self._comparator_class() self.before_client_main_recompile() # get ready right away return def deallocate_displists(self): self.csdl.deallocate_displists() def updateTransform(self): self.csdl.updateTransform() # == methods related to the client compiling its *main* display list # (not this extra one, but that's when it finds out what goes into # this extra one, or that it needs it at all) def before_client_main_recompile(self): #e rename? self._drawing_functions = [] return # During client main recompile. def add_another_drawing_function(self, func): self._drawing_functions.append( func) return def after_client_main_recompile(self): #e rename? ### todo: CALL THIS (when I figure out where to call it from) # (not urgent until it needs to do something) return # == methods for drawing self (with or without recompiling) def draw_but_first_recompile_if_needed( self, glpane, selected = False, highlighted = False, wantlist = True, draw_now = True ): """ Recompile self as needed, then (unless draw_now = False) draw. Only make internal display lists (in cases where we need to remake them) if wantlist is true; otherwise draw_now is required. @param selected: whether to draw in selected or plain style. (The same csdl handles both.) @param highlighted: whether to draw highlighted, or not. (The same csdl handles both.) """ graphicsMode = glpane.graphicsMode # note: ThumbView lacks this attribute; # for now, client code in ChunkDrawer worries about this, # and won't call us then. [bruce 080606 comment] context = graphicsMode if self.comparator.do_we_need_to_recompute(context): # maybe: also compare havelist, if some data not tracked if DEBUG_COMPARATOR: print "_draw_by_remaking in %r; valid = %r" % \ (self, self.comparator.valid) self._draw_by_remaking(glpane, selected, highlighted, wantlist, draw_now) elif draw_now: if DEBUG_COMPARATOR: print "_draw_by_reusing in %r" % self self._draw_by_reusing(glpane, selected, highlighted) return def _draw_by_remaking(self, glpane, selected, highlighted, wantlist, draw_now): """ """ # modified from similar code in ChunkDrawer.draw assert not (not wantlist and not draw_now) if wantlist: match_checking_code = self.begin_tracking_usage() # note: method defined in superclass, SubUsageTrackingMixin ColorSorter.start(glpane, self.csdl, selected) ### REVIEW: is selected arg needed? guess yes, # since .finish will draw it based on the csdl state # which is determined by that arg. If so, this point needs # correcting in the docstring for csdl.draw(). self.comparator.before_recompute() try: self._do_drawing() except: print_compact_traceback( "bug: exception in %r._do_drawing, skipping the rest: " % self) self.comparator.after_recompute() # note: sets self.comparator.valid (in spite of error) pass else: self.comparator.after_recompute() if wantlist: ColorSorter.finish(draw_now = draw_now) # needed by self._invalidate_display_lists for gl_update self._glpane = glpane self.end_tracking_usage( match_checking_code, self._invalidate_display_lists ) return def _draw_by_reusing(self, glpane, selected, highlighted): """ @see: self.draw """ self.csdl.draw(selected = selected, highlighted = highlighted) return def draw(self, **kws): #bruce 090224; probably not needed or ever called """ Draw self, accepting the same keyword args that CSDL.draw does. @note: doesn't remake us, or notice any error, if we need remaking. @see: self._draw_by_reusing (which doesn't take all the args we do) """ self.csdl.draw(**kws) return # == def invalidate(self): self.comparator.invalidate() return def _invalidate_display_lists(self): """ This is meant to be called when something whose usage we tracked (while making our display list) next changes. """ # print "fyi: called %r._invalidate_display_lists" % self # this happens self.invalidate() self._glpane.gl_update() # self._glpane should always exist return # == def _do_drawing(self): # drawsphere(...), drawcylinder(...), drawpolycone(...), and so on. args = self._construct_args_for_drawing_functions() for func in self._drawing_functions: func(*args) return def _construct_args_for_drawing_functions(self): assert 0, "subclass must implement" pass # end of class ExtraChunkDisplayList # == class SpecialDrawing_ExtraChunkDisplayList(ExtraChunkDisplayList): """ """ # note about current usage by client code (chunk drawing code): # this will be created on demand when something being drawn # during a chunk's main displist (CSDL) compile # wants to put things into a StrandEnd display list instead, # since that might need recompiling more often than the main one. # The chunk knows which subclass of ExtraChunkDisplayList to use # for each type of extra drawing, and allocates one on demand. # Then the object doing the drawing will give us a function # to use for redrawing itself, passing it to add_another_drawing_function. # subclass constants _comparator_class = SpecialDrawing_UsedValueTrackerAndComparator # overridden methods def _construct_args_for_drawing_functions(self): ## prefs_value_finder = USE_CURRENT # KLUGE, but should partly work -- ## # we should construct one that uses the current glpane, ## # but this one knows how to find it... ## # but WRONG since it fails to do tracking as it ought to... ## # namely through our own get_value call, with context = the GM. # ideally (non klugy): know glpane, and wrap self.comparator with it, # and give that wrapper a __getitem__ interface. # actual code: use our comparator subclass directly, give it # __getitem__, and make it find glpane dynamically (KLUGE). prefs_value_finder = self.comparator return (prefs_value_finder,) pass # end of class # === class Chunk_SpecialDrawingHandler(object): """ A kind of SpecialDrawingHandler for a ChunkDrawer. (There is not yet any other kind; what we know about class ChunkDrawer is mainly the names of a few of its attributes we use and modify -- I guess just chunkdrawer.extra_displists, a dict from special_drawing_kind to subclasses of ExtraChunkDisplayList.) A SpecialDrawingHandler is .... #doc """ def __init__(self, chunkdrawer, classes): """ @param classes: a dict from special_drawing_kinds to subclasses of ExtraChunkDisplayList whose method _construct_args_for_drawing_functions returns a tuple of one argument, namely a prefs_value_finder which maps __getitem__ to get_value of a SpecialDrawing_UsedValueTrackerAndComparator; the only suitable class as of 080605 is SpecialDrawing_ExtraChunkDisplayList. """ self.chunkdrawer = chunkdrawer self.classes = classes return def should_defer(self, special_drawing_kind): assert special_drawing_kind in ALL_SPECIAL_DRAWING_KINDS return self.classes.has_key(special_drawing_kind) #e rename? def draw_by_calling_with_prefsvalues(self, special_drawing_kind, func): # print "fyi: draw_by_calling_with_prefsvalues got", \ # special_drawing_kind, func # This happens. extra_displist = self._get_extra_displist(special_drawing_kind) extra_displist.add_another_drawing_function( func) return def _get_extra_displist(self, special_drawing_kind): """ Find or make, and return, the right kind of ExtraChunkDisplayList for the given special_drawing_kind. """ # review: does some or all of this belong in our client, # self.chunkdrawer (in some method we'd call back to)? extra_displists = self.chunkdrawer.extra_displists # a dict from kind to extra_displist try: return extra_displists[special_drawing_kind] except KeyError: class1 = self.classes[special_drawing_kind] transformControl = self.chunkdrawer.getTransformControl() new = class1(transformControl) extra_displists[special_drawing_kind] = new return new pass pass # end of class # end
NanoCAD-master
cad/src/graphics/model_drawing/special_drawing.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ bond_drawer.py -- implementations of Bond.draw and Bond.writepov. @author: Josh, Bruce @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: 050727 bruce moved bodies of Bond.draw and Bond.writepov into functions in this file, in preparation for further extending Bond.draw (and someday Bond.writepov) for higher-order bonds. 090213 bruce refiled this module into graphics.model_drawing package """ from OpenGL.GL import glPushName from OpenGL.GL import glPopName from OpenGL.GL import GL_LIGHTING from OpenGL.GL import glDisable from OpenGL.GL import glEnable from PyQt4.Qt import QFont, QString, QColor from geometry.VQT import V from geometry.VQT import norm, vlen from graphics.drawing.ColorSorter import ColorSorter from graphics.drawing.CS_draw_primitives import drawline from graphics.drawing.CS_draw_primitives import drawcylinder from graphics.drawing.CS_draw_primitives import drawsphere from graphics.model_drawing.special_drawing import USE_CURRENT from graphics.model_drawing.special_drawing import SPECIAL_DRAWING_STRAND_END import foundation.env as env from utilities import debug_flags from graphics.rendering.povray.povheader import povpoint from utilities.Printing import Vector3ToString from model.elements import Singlet from utilities.debug import print_compact_stack, print_compact_traceback from utilities.constants import diDEFAULT from utilities.constants import diINVISIBLE from utilities.constants import diLINES from utilities.constants import diBALL from utilities.constants import diTUBES from utilities.constants import diTrueCPK from utilities.constants import diDNACYLINDER from utilities.constants import TubeRadius from utilities.constants import diBALL_SigmaBondRadius from utilities.constants import diDNACYLINDER_SigmaBondRadius from utilities.constants import ave_colors from utilities.constants import green from utilities.constants import yellow from utilities.constants import red from utilities.constants import blue from utilities.constants import black from utilities.constants import white from utilities.constants import orange from utilities.constants import lighterblue from model.bond_constants import V_SINGLE from model.bond_constants import V_DOUBLE from model.bond_constants import V_TRIPLE from model.bond_constants import bond_letter_from_v6 from model.bond_constants import V_AROMATIC from model.bond_constants import V_GRAPHITE from model.bond_constants import V_CARBOMERIC ## not yet in prefs db? from utilities.prefs_constants import _default_toolong_hicolor from utilities.prefs_constants import diBALL_BondCylinderRadius_prefs_key from utilities.prefs_constants import diDNACYLINDER_BondCylinderRadius_prefs_key from utilities.prefs_constants import pibondLetters_prefs_key from utilities.prefs_constants import pibondStyle_prefs_key from utilities.prefs_constants import arrowsOnFivePrimeEnds_prefs_key from utilities.prefs_constants import arrowsOnThreePrimeEnds_prefs_key from utilities.prefs_constants import arrowsOnBackBones_prefs_key from utilities.prefs_constants import showBondStretchIndicators_prefs_key from utilities.prefs_constants import linesDisplayModeThickness_prefs_key from utilities.prefs_constants import bondStretchColor_prefs_key from utilities.prefs_constants import diBALL_bondcolor_prefs_key from utilities.prefs_constants import dnaStrutScaleFactor_prefs_key from utilities.GlobalPreferences import disable_do_not_draw_open_bonds # == # To modularize drawing, I'll pass in a drawing place which has methods like # drawcylinder, which can be either the drawer module itself (or an object made # here to encapsulate it) or a writepov-to-specific-file object. This is # experimental code, so for now it's only here in bond_drawer.py. # # In the future, it should be created once per writepov event, and write the # povheader, and then it should be passed in to individual writepov # routines. Farther ahead, it should be able to write new macros which embody # env.prefs values as needed, so individual atom/bond drawing calls don't need # to each incorporate the effects of prefs values, but so that single macros can # be revised manually in the output file to effectively change prefs values (a # longstanding NFR from the SAB). # # [bruce 060622] class writepov_to_file: def __init__(self, file, col = None): self.file = file # a file object, not just its name # does not currently write the povheader, assumes it was already written self.bondColor = col return # for now, the following methods have the same names and arg orders as the # macro calls that were used directly in writepov_bond. def line(self, a1pos, a2pos, color): self.file.write("line(" + povpoint(a1pos) + "," + povpoint(a2pos) + ", <" + str(color[0]) +"," + str(color[1]) + ", " + str(color[2]) + ">)\n") def writeradmacro(self, rad, radmacro, noradmacro): if rad is not None: self.file.write("%s(" % radmacro + str(rad) + ", " ) else: self.file.write("%s(" % noradmacro ) def bond(self, a1pos, a2pos, col, rad = None): self.writeradmacro(rad, "bondr", "bond") self.file.write(povpoint(a1pos) + "," + povpoint(a2pos) + "," + Vector3ToString(col) + ")\n") def tube3(self, a1pos, a2pos, col, rad = None): self.writeradmacro(rad, "tube3r", "tube3") self.file.write(povpoint(a1pos) + ", " + povpoint(a2pos) + ", " + Vector3ToString(col) + ")\n") def tube2(self, a1pos, color1, center, a2pos, color2, rad = None): if 1: #e Possible optim: if color1 == color2, this could reduce to tube3. # That might speed up povray in tubes mode by a factor of 2 or so # (for bonds that are not toolong), or maybe by 5/4 if half of the # bonds are toolong. It seems to work (from manual inspection of # the output) so I'll leave it in. [bruce 060622] if color1 == color2: self.tube3(a1pos, a2pos, color1, rad) return self.writeradmacro(rad, "tube2r", "tube2") self.file.write(povpoint(a1pos) + "," + Vector3ToString(color1) + "," + povpoint(center) + "," + povpoint(a2pos) + "," + Vector3ToString(color2) + ")\n") def tube1(self, a1pos, color1, c1, c2, a2pos, color2, rad = None): self.writeradmacro(rad, "tube1r", "tube1") self.file.write(povpoint(a1pos) + "," + Vector3ToString(color1) + "," + povpoint(c1) + "," + povpoint(c2) + "," + povpoint(a2pos) + "," + Vector3ToString(color2) + ")\n") # arg order compatible with drawer.drawcylinder def drawcylinder(self, color, pos1, pos2, radius): self.tube3(pos1, pos2, color, radius) # Arg order compatible with drawer.drawsphere, except no detailLevel; not # yet called or tested. [060622] def drawsphere(self, color, pos, radius): ###k not compared with other calls of atom macro, or tested; kluge that ###it uses atom macro, since not all spheres are atoms self.file.write("atom(" + str(pos) + ", " + str(radius) + ", " + Vector3ToString(color) + ")\n") def getBondColor(self): """ Returns the self.bondColor (rgb value) @return: L{self.bondColor} @see: L{self.old_writepov_bondcyl} @Note: this whole file needs code cleanup. """ return self.bondColor # == def bond_draw_in_CPK(self): #bruce 080212 # todo: make this a Bond method """ Should the bond 'self' be drawn in CPK display mode? """ if self.is_rung_bond(): return False dispjunk, radius1 = self.atom1.howdraw(diTrueCPK) # inline for speed?? dispjunk, radius2 = self.atom2.howdraw(diTrueCPK) # use baseposn for speed? (would only be correct for internal bonds) pos1 = self.atom1.posn() pos2 = self.atom2.posn() # don't bother drawing if atoms touch, even if some of self would be visible # if they just barely touch. return ( vlen(pos1 - pos2) > radius1 + radius2 ) def draw_bond(self, glpane, dispdef, col, detailLevel, highlighted = False, special_drawing_handler = None, special_drawing_prefs = USE_CURRENT ): #bruce 050702 adding shorten_tubes option; # 050727 that's now implied by new highlighted option. """ Draw the bond 'self'. This function is only meant to be called as the implementation of Bond.draw. See that method's docstring for details of how it's called. The highlighted option says to modify our appearance as appropriate for being highlighted (but the highlight color, if any, is passed as a non-false value of col). """ atom1 = self.atom1 atom2 = self.atom2 disp = max(atom1.display, atom2.display) if disp == diDEFAULT: disp = dispdef # piotr 080312 if disp == diDNACYLINDER: return if disp in (diTrueCPK, diDNACYLINDER): # new feature (previously we never drew these bonds): # only draw the bond if it's sufficiently long to be visible # and not a "dna rung bond". # warning: this code is duplicated in two places in this file. # [bruce 080212, after discussion] if bond_draw_in_CPK(self): # Determines bond thickness and style; might be revised. disp = diDNACYLINDER else: return if disp not in (diLINES, diBALL, diTUBES, diDNACYLINDER): return # set proper glname, for highlighting (must be done whether or not # highlighted is true) if atom1.element is Singlet: #bruce 050708 new feature -- borrow name from our singlet # (only works because we have at most one) # (also required a change in Atom.draw_in_abs_coords) glname = atom1.get_glname(glpane) elif atom2.element is Singlet: glname = atom2.get_glname(glpane) else: glname = self.glname ColorSorter.pushName(glname) #bruce 051206, part of fixing bug 1179 # for non-open bonds; we have to do it both immediately and in # ColorSorter since bonds include both sorted and non-sorted openGL # drawing. Note, we don't yet protect against sorting not being active # now, but that should be fixed in drawer.py rather than here, and for # now it will always be active since all bond drawing in chunk.py is # done inside it (even external bonds). glPushName(glname) #bruce 050610 # Note: we have to do this all the time, since display lists made # outside GL_SELECT mode can be used inside it. And since that display # list might be used arbitrarily far into the future, self.glname needs # to remain the same (and we need to remain registered under it) as long # as we live. try: #bruce 050610 to ensure calling glPopName povfile = None draw_bond_main(self, glpane, disp, col, detailLevel, highlighted, povfile, special_drawing_handler = special_drawing_handler, special_drawing_prefs = special_drawing_prefs, glname = glname ) except: glPopName() #bruce 060622 moved this before ColorSorter.popName print_compact_traceback( "ignoring exception when drawing bond %r: " % self) ColorSorter.popName() #bruce 051206 else: glPopName() ColorSorter.popName() #bruce 051206 return # from draw_bond, implem of Bond.draw def draw_bond_main(self, glpane, disp, col, detailLevel, highlighted, povfile = None, special_drawing_handler = None, special_drawing_prefs = USE_CURRENT, glname = None # glname arg is a kluge for fixing bug 2945 ): """ [private helper function for this module only.] self is a bond. For other doc, see the calls. """ _our_args = (self, glpane, disp, col, detailLevel, highlighted, povfile) # This must be kept in agreement with all args of this function except # special_*. We include self in the tuple, since this function is not a # method. [bruce 080605] # figure out how this display mode draws bonds; return now if it doesn't # [moved inside this function, bruce 060622] if disp == diLINES: sigmabond_cyl_radius = diBALL_SigmaBondRadius / 5.0 # used for multiple bond spacing (optimized here for that, by the "/ # 5.0") and for pi orbital vanes (for which "/ 1.0" would probably # be better) elif disp == diBALL: # Used for single, double and triple bonds. sigmabond_cyl_radius = diBALL_SigmaBondRadius \ * env.prefs[diBALL_BondCylinderRadius_prefs_key] # mark 051003 added. elif disp == diTUBES: sigmabond_cyl_radius = TubeRadius elif disp == diDNACYLINDER: # diDNACYLINDER_BondCylinderRadius_prefs_key is not yet settable by # user. It's value is 1.0. Mark 2008-02-13. sigmabond_cyl_radius = diDNACYLINDER_SigmaBondRadius \ * env.prefs[diDNACYLINDER_BondCylinderRadius_prefs_key] else: # bonds need not be drawn at all in the other display modes. (note: some # callers already checked this.) return # Figure out preferences. (Should do this less often somehow -- once per # user event, or at least, once per separate use of # begin_tracking_usage/end_tracking_usage.) if self.v6 != V_SINGLE: if debug_flags.atom_debug: #bruce 050716 debug code (permanent, since this would always # indicate a bug) if not self.legal_for_atomtypes(): print_compact_stack( "atom_debug: drawing bond %r %s" % (self, "which is illegal for its atomtypes: ")) if povfile is not None: # not yet supported, and i worry about side effects of env usage # tracking. draw_bond_letters = False else: draw_bond_letters = (not highlighted and env.prefs[ pibondLetters_prefs_key]) # One of ['multicyl','vane','ribbon']. pi_bond_style = env.prefs[ pibondStyle_prefs_key] draw_cyls = (pi_bond_style == 'multicyl') draw_vanes = not draw_cyls # this is true for either vanes or ribbons draw_sigma_cyl = not draw_cyls if povfile is not None: draw_vanes = False # not yet supported else: # single bond -- no need to check prefs or set variables for vanes, etc draw_cyls = False draw_sigma_cyl = True # Whether to ever draw bands around the cylinders for aromatic/graphite # bonds. draw_bands = draw_cyls if draw_bands: v6_for_bands = self.v6 else: v6_for_bands = V_SINGLE shorten_tubes = highlighted # Usual case for non-directional bonds; draws nothing; change this below if # necessary. dir_info = (0, False) direction_error = False # change below if necessary if self._direction: #bruce 070415, revised 071016 # We might want to show this bond's direction, or (someday) # its ability to have one. Figure out what to actually show. if not self.is_directional(): direction_error = True # but no sensible way to set dir_info, so leave it as default, # partly to avoid other errors in the else case # which assumes the bond is directional. else: # apply this general pref test first, to be faster when it's turned # off. # ninad070504: added the bond arrows preferences to Preferences # dialog. using this preference key instead of debug preference. ### POSSIBLE BUG (by experience, not understood in code, not # always repeatable): changing this debug_pref [back when the # following prefs were debug_prefs] fails to redraw internal # bonds accordingly (tho fine for external bonds). This is as # if it's not usage tracked by the chunk display list compile, # or as if the change to it via the debug menu is not change # tracked. # Workaround (not very convenient): Undo past where you created # the DNA, and redo. # Or, probably, just change the chunk display style. # The bug is not always repeatable: I changed display to cpk # (all arrows gone, finally correct), then back to tubes, then # turned arrows on, and this time they all showed up, and again # as I try off/on. # Maybe it was an artifact of reloading this code?? # [bruce 070415] # update, bruce 071016: could it have been simply that # debug_prefs are not change_tracked? I am not sure, but IIRC, # they're not. if self.isFivePrimeOpenBond() or \ self.isThreePrimeOpenBond(): # draw self into the "strand end" display list, if caller has # one [bruce 080605] if (special_drawing_handler and special_drawing_handler.should_defer( SPECIAL_DRAWING_STRAND_END)): # defer all drawing of self to special_drawing_handler def func(special_drawing_prefs, args = _our_args, glname = glname): # KLUGE to fix bug 2945: make sure we do the same # pushname/popname as the caller has already done, # since draw_bond_main doesn't otherwise do it. # This is the true cause of bug 2945 and this fix is # logically correct; I only call it a kluge because # the code needs cleanup, at least in this file # (so the pushname is only done in one place), # but preferably by just making sure all open bonds # are always drawn as part of drawing their bondpoints, # which would allow a bunch of code which now has to be # kept in correspondence between bond and atom drawing # to be centralized and simplified. [bruce 081211] ColorSorter.pushName(glname) # review: also need glPushName? try: draw_bond_main( *args, **dict(special_drawing_prefs = special_drawing_prefs)) finally: ColorSorter.popName() return # from func special_drawing_handler.draw_by_calling_with_prefsvalues( SPECIAL_DRAWING_STRAND_END, func ) return # otherwise, draw now, using special_drawing_prefs _disable_do_not_draw = disable_do_not_draw_open_bonds() # for debugging [bruce 080122] # Determine whether cylinders of strand open bonds should be # drawn. Atom._draw_atom_style() takes care of drawing singlets # as arrowheads (or not drawing them at all) based on these two # user prefs. - mark 2007-10-20. if self.isFivePrimeOpenBond(): if not special_drawing_prefs[ arrowsOnFivePrimeEnds_prefs_key]: # Don't draw bond 5' open bond cylinder. if _disable_do_not_draw: if not highlighted and debug_flags.atom_debug: #bruce 800406 Revised color & cond. col = lighterblue pass pass else: return if self.isThreePrimeOpenBond(): if not special_drawing_prefs[ arrowsOnThreePrimeEnds_prefs_key]: # Don't draw bond 3' open bond cylinder. if _disable_do_not_draw: if not highlighted and debug_flags.atom_debug: col = lighterblue pass pass else: return pass pass # note: This might fall through -- only some cases above return. pass # If we didn't defer, we don't need to use special_drawing_handler # at all. del special_drawing_handler del special_drawing_prefs # not used below (fyi) bool_arrowsOnAll = env.prefs[arrowsOnBackBones_prefs_key] if bool_arrowsOnAll: # Draw arrow on bond unless there is some reason not to. # If either atom will look like an arrowhead (before prefs are # applied) -- i.e. if either one is a strand_end -- we don't # want the bond to have its own arrowhead. [bruce 071016, # feature requested by mark] # update, bruce 071018 -- an arrow-atom in front should always # suppress self's arrow, but an arrow atom in back should only # turn it off if self is an open bond, since we draw the arrow # only on the front half of the bond. (Front and back are # relative to self's bond_direction.) # These flags might be changed during the following loop. direction_error = False suppress_self_arrow_always = False # Set by arrowhead in front. # Set by arrowhead in back. suppress_self_arrow_if_open_bond = False for atom in (self.atom1, self.atom2): # Does atom look like an arrowhead (i.e end_bond is not # None), and if so, should that suppress_self_arrow? end_bond = atom.strand_end_bond() if end_bond is self: if atom.is_singlet(): suppress_self_arrow_always = True elif self.bond_direction_from(atom) == -1: # atom is in front suppress_self_arrow_always = True else: # Atom is in back (since we know self has a # direction set.) suppress_self_arrow_if_open_bond = True elif end_bond is not None: # end_bond not None or self -- We're directional, but # not the directional bond atom thinks is a strand end! # Error or bug, so always show self's arrow too. ## REVIEW: are there other bond direction errors we need ## to indicate as well? direction_error = True continue if suppress_self_arrow_if_open_bond and self.is_open_bond(): suppress_self_arrow_always = True if direction_error or not suppress_self_arrow_always: dir_info = (self.bond_direction_from(self.atom1), True) pass pass pass # do calcs common to all bond-cylinders for multi-cylinder bonds atom1 = self.atom1 atom2 = self.atom2 color1 = col or atom1.drawing_color() color2 = col or atom2.drawing_color() ## if None, we look up the value when it's used [bruce 050805] bondcolor = col or None # note: bondcolor is only used in diBALL display style. todo: rename it. if (direction_error or atom1._dna_updater__error or atom2._dna_updater__error): # bruce 080130 added _dna_updater__error condition; not sure if 'and' or # 'or' is better in it; for now, use 'and' below for color, but use 'or' # for a debug print. The outer condition is to optimize the usual case # where all these are false. if not highlighted: #bruce 080406 added "not highlighted" condition as bugfix # (this also required a bugfix in Bond.draw_in_abs_coords to pass # highlighted = True for external bonds) if (direction_error or (atom1._dna_updater__error and atom2._dna_updater__error)): # note: no effect except in diBALL display style bondcolor = orange # Work around bug in uses above of drawing_color method: # [bruce 080131] if atom1._dna_updater__error or direction_error: color1 = orange # todo: also change toolong_color if we can if atom2._dna_updater__error or direction_error: color2 = orange # todo: also change toolong_color if we can if atom1._dna_updater__error or atom2._dna_updater__error: if not atom1._dna_updater__error and atom2._dna_updater__error: # Debug print if self is a rung bond (means error in dna # updater.) # Note: always on, for now; # TODO: condition on DEBUG_DNA_UPDATER but first move that out # of dna package roles = (atom1.element.role, atom2.element.role) # Inlined self.is_rung_bond() . if roles == ('axis', 'strand') or roles == ('strand', 'axis'): print ("\n*** bug in dna updater: %s %r" % ("errors not propogated along", self)) #bruce 071016 (tentative -- needs mouseover msg, as said above) # (TODO: we could set an error message string on self, but set it to # None whenever not setting the error color; since this is done whenever # self is redrawn, it will always be up to date when highlighting or # tooltip happens.) v1 = atom1.display != diINVISIBLE v2 = atom2.display != diINVISIBLE ###e bruce 041104 suspects v1, v2 wrong for external bonds, needs # to look at each mol's .hidden (but this is purely a guess) # compute geometry (almost always needed eventually, below) fix_geom = (povfile is not None) and (atom1.molecule is atom2.molecule) if fix_geom: # in this case, bond.geom is wrong, needs to be absolute but isn't selfgeom = self._recompute_geom(abs_coords = True) else: #e perhaps could be optimized to only compute a1pos, a2pos selfgeom = self.geom howmany = 1 # modified below if draw_cyls: # Draw 1, 2, or 3 central cyls, depending on bond type (only 1 for # aromatic bonds) (#e what's best for carbomeric?) # Note: this code sets howmany, and if it's not 1, draws that many cyls; # otherwise howmany == 1 is noticed below (not inside this 'if' # statement) so the central cyl is drawn. howmany = { V_DOUBLE: 2, V_TRIPLE: 3 }.get(self.v6, 1) if howmany > 1: # Figure out where to draw them, and cyl thickness to use; this # might depend on disp and/or on sigmabond_cyl_radius . if fix_geom: pi_info = self.get_pi_info(abs_coords = True) else: #k This could probably be the same call as above, with # abs_coords = fix_geom . pi_info = self.get_pi_info() pass if pi_info is None: # Should never happen; # if it does, work around the bug this way. howmany = 1 else: # Vectors are in bond's coordsys. ((a1py, a1pz), (a2py, a2pz), ord_pi_y, ord_pi_z) = pi_info del ord_pi_y, ord_pi_z pvecs1 = multicyl_pvecs(howmany, a1py, a1pz) # Leaves them as unit vectors for now. pvecs2 = multicyl_pvecs(howmany, a2py, a2pz) if disp == diLINES: # Arbitrary, since cylinder thickness is not used when # drawing lines. scale = 1 offset = 2 elif disp == diBALL: scale = 1 offset = 2 # in units of sigmabond_cyl_radius elif disp == diTUBES: # I don't like this being so small, but it's in the spec. scale = 0.333 offset = 0.333 * 2 else: # pure guesses; used for diTrueCPK and diDNACYLINDER # [bruce 080213] scale = 0.333 offset = 0.333 * 2 # now modify geom for these other cyls a1pos, c1, center, c2, a2pos, toolong = selfgeom del c1, center, c2, toolong cylrad = scale * sigmabond_cyl_radius offset *= sigmabond_cyl_radius # use this offset in the loop for pvec1, pvec2 in zip(pvecs1, pvecs2): a1posm = a1pos + offset * pvec1 a2posm = a2pos + offset * pvec2 # Correct in either abs or rel coords. geom = self.geom_from_posns(a1posm, a2posm) draw_bond_cyl(atom1, atom2, disp, v1, v2, color1, color2, bondcolor, highlighted, detailLevel, cylrad, shorten_tubes, geom, v6_for_bands, povfile, dir_info ) if draw_sigma_cyl or howmany == 1: # draw one central cyl, regardless of bond type geom = selfgeom #e could be optimized to compute less for CPK case cylrad = sigmabond_cyl_radius draw_bond_cyl(atom1, atom2, disp, v1, v2, color1, color2, bondcolor, highlighted, detailLevel, cylrad, shorten_tubes, geom, v6_for_bands, povfile, dir_info ) if self.v6 != V_SINGLE: if draw_vanes: if debug_flags.atom_debug: import graphics.drawing.draw_bond_vanes as draw_bond_vanes import utilities.debug as debug #bruce 050825 renabled this, using reload_once_per_event debug.reload_once_per_event(draw_bond_vanes) pass from graphics.drawing.draw_bond_vanes import draw_bond_vanes # This calls self.get_pi_info(). draw_bond_vanes(self, glpane, sigmabond_cyl_radius, col) pass if draw_bond_letters and glpane.permit_draw_bond_letters: # note: bruce 071023 added glpane.permit_draw_bond_letters to # replace this test and remove some import cycles: ## isinstance(glpane, MMKitView): # [Huaicai 11/14/05: added the MMKitView test to fix bug 969,884] # # Ideally, it would be better to disable the bond letter feature # completely in the MMKit thumbview for Library, but not for single # atoms (though those use the same glpane)... could we do this by # testing ratio of atomcount to glpane size? or by the controlling # code setting a flag? (For now, just ignore the issue, and disable # it in all thumbviews.) [bruce 051110/071023] try: glpane_out = glpane.out except AttributeError: # kluge for Element Selector [bruce 050507 bugfix] glpane_out = V(0.0, 0.0, 1.0) pass textpos = self.center + glpane_out * 0.6 # Note -- this depends on the current rotation when the display # list is made! But it's ok for now. We could fix this by # having a separate display list, or no display list, for these # kinds of things -- would need a separate display list per # chunk and per offset. Not worth it for now. text = bond_letter_from_v6(self.v6).upper() text_qcolor = QColor(255, 255, 255) # white # fontname and fontsize: only some combos work, e.g. Times 10 # (maybe) but not 12, and Helvetica 12 but not 10, and this might be # platform-dependent; when it fails, for Mac it just draws nothing # (bug 1113) but for Windows & Linux it tracebacks (bug 1112). So # to fix those bugs, I'm just using the same fontname/fontsize as in # all our other renderText calls. # (Some of those have pushMatrix but that is not needed. Most of # those disable depth test, but that looks bad here and is also not # needed. We don't call drawer.drawtext since it always disables # depth test.) [bruce 051111] font = QFont(QString("Helvetica"), 12) ###e should adjust fontsize based on scale, depth... (if not for ### the bugs mentioned above) #e should construct font only once, keep in glpane glDisable(GL_LIGHTING) glpane.qglColor(text_qcolor) p = textpos #k need explicit QString?? glpane.renderText(p[0], p[1], p[2], QString(text), font) ### BUG: it seems that this text is not stored in display lists. # Evidence: for external bonds (not presently in display lists) # this works reliably, but for internal bonds, it seems to only # get rendered when the display list is remade (e.g. when one # of the chunk's atoms is selected), not when it's redrawn # (e.g. for redraws due to highlighting or viewpoint changes). # I know that in the past (when this was first implemented), # that was not the case (since rotating the chunk made the bond # letters show up in the wrong direction due to glpane.out # no longer being valid). It might be a new bug with Qt 4 -- # I'm not sure how new it is. # [bruce 081204 comment] # bug 969 traceback (not on Mac) claims "illegal OpenGL op" in this # line! [as of 051110 night] [which line?] glEnable(GL_LIGHTING) pass pass return # from draw_bond_main def multicyl_pvecs(howmany, a2py, a2pz): if howmany == 2: # note, for proper double-bond alignment, this has to be a2py, not a2pz! return [a2py, -a2py] elif howmany == 3: # 0.866 is sqrt(3)/2 return [a2py, - a2py * 0.5 + a2pz * 0.866, - a2py * 0.5 - a2pz * 0.866] else: assert 0 pass def draw_bond_cyl(atom1, atom2, disp, v1, v2, color1, color2, bondcolor, highlighted, detailLevel, sigmabond_cyl_radius, shorten_tubes, geom, v6, povfile, dir_info ): """ Draw one cylinder, which might be for a sigma bond, or one of 2 or 3 cyls for double or triple bonds. [private function for a single caller, which is the only reason such a long arglist is tolerable] """ a1pos, c1, center, c2, a2pos, toolong = geom #following turns off the bond stretch indicators based on the user #preference bool_showBondStretch = env.prefs[showBondStretchIndicators_prefs_key] if not bool_showBondStretch: toolong = False # kluge, bruce 080130: if (atom1._dna_updater__error and atom2._dna_updater__error): toolong = False # If atom1 or atom2 is a PAM atom, we recompute the sigmabond_cyl_radius. # After experimenting, the standard <TubeRadius> works well for the # standard radius for both diBALL and diTUBES display styles. # This is multiplied by the "DNA Strut Scale Factor" user preference to # compute the final radius. Mark 2008-01-31. ### REVIEW: is this correct for diTrueCPK and/or diDNACYLINDER? ### [bruce comment 080213] if (atom1.element.pam or atom2.element.pam): if disp == diBALL or disp == diTUBES: # The following increases the radius of the axis bonds by the # 'axisFactor'. The new radius makes it easy to drag the dna segment # while in DnaSegment_EditCommand. Another possibility is to # increase this radius only in DnaSegment_EditCommand. But # retrieving the current command information in this method may not # be straigtforward and is infact kludgy (like this) The radius of # axis bonds was increased per Mark's request for his presentation # at FNANO08 -- Ninad 2008-04-22 if atom1.element.role == 'axis' and atom2.element.role == 'axis': axisFactor = 2.0 else: axisFactor = 1.0 sigmabond_cyl_radius = \ TubeRadius * env.prefs[dnaStrutScaleFactor_prefs_key]*axisFactor # Figure out banding (only in CPK [review -- old or true cpk?] or Tubes # display modes). This is only done in multicyl mode, because caller makes # our v6 equal V_SINGLE otherwise. If new color args are needed, they # should be figured out here (perhaps by env.prefs lookup). This code ought # to be good enough for A6, but if Mark wants to, he and Huaicai can modify # it in this file. [bruce 050806] if v6 == V_AROMATIC: # Use aromatic banding on this cylinder (bond order 1.5). banding = V_AROMATIC band_color = ave_colors(0.5, green, yellow) elif v6 == V_GRAPHITE: # Use graphite banding on this cylinder (bond order 1.33). banding = V_GRAPHITE band_color = ave_colors(0.8, green, yellow) elif v6 == V_CARBOMERIC: # Use carbomeric banding on this cylinder (bond order 2.5) (length is # same as aromatic for now). banding = V_AROMATIC band_color = ave_colors(0.7, red, white) else: banding = None # no banding needed on this cylinder if banding and disp not in (diBALL, diTUBES): # review: do we want banding in diTrueCPK as well? # todo: if this ever happens, could optimize above instead banding = None if banding: # 0.33, 0.5, or for carbomeric, in principle 1.5 but in practice 0.5 band_order = float(banding - V_SINGLE)/V_SINGLE bandvec = (a2pos - a1pos)/2.0 # from center to a2pos # If this was 1 we'd cover it entirely; this is measured to atom # centers, not just visible part... bandextent = band_order/2.5 bandpos1 = center - bandvec * bandextent bandpos2 = center + bandvec * bandextent if highlighted: band_color = ave_colors(0.5, band_color, blue) band_color = ave_colors(0.8, band_color, black) # End of figuring out banding, though to use it, the code below must be # modified. if povfile is not None: # Ideal situation, worth doing when we have time: # if povfile had the equivalent of drawcylinder and drawsphere (and took # radius prefs into account in tube macros), we could just run the # non-povfile code below on it, and get identical pov and non-pov # rendering. # (for bonds, incl multicyl and banded, tho not for vanes/ribbons or # bond letters or half-invisible bonds # (with spheres -- not so great a feature anyway) # until other code is modified and povfile has a few more primitives # needed for those). # # Current situation: for povfiles, we just replace the rest of this # routine with the old povfile bond code, modified to use macros that # take a radius, plus a separate call for banding. This should cover: # multiple cyls, banding, radius prefs; but won't cover: color prefs, # other fancy things listed above. [bruce 060622] # # It also doesn't yet cover the debug_pref "draw arrows on all # directional bonds?" -- i.e. for now that does not affect # POV-Ray. [bruce 070415] old_writepov_bondcyl(atom1, atom2, disp, a1pos, c1, center, c2, a2pos, toolong, color1, color2, povfile, sigmabond_cyl_radius) if banding and disp in (diBALL, diTUBES): povfile.drawcylinder(band_color, bandpos1, bandpos2, sigmabond_cyl_radius * 1.2) return a1pos_not_shortened = + a1pos a2pos_not_shortened = + a2pos if disp == diLINES: width = env.prefs[linesDisplayModeThickness_prefs_key] #bruce 050831 if width <= 0: # fix illegal value to prevent exception width = 1 if not toolong: drawline(color1, a1pos, center, width = width) drawline(color2, a2pos, center, width = width) else: drawline(color1, a1pos, c1, width = width) drawline(color2, a2pos, c2, width = width) toolong_color = env.prefs.get(bondStretchColor_prefs_key) # toolong_color is never highlighted here, since we're not sure # highlighting bonds in LINES mode is good at all drawline(toolong_color, c1, c2, width = width) elif disp == diBALL: if bondcolor is None: #bruce 050805 ## bondColor [before bruce 050805] bondcolor = env.prefs.get(diBALL_bondcolor_prefs_key) pass drawcylinder(bondcolor, a1pos, a2pos, sigmabond_cyl_radius) if banding: drawcylinder(band_color, bandpos1, bandpos2, sigmabond_cyl_radius * 1.2) elif disp == diDNACYLINDER: # note: this case is also used for diTrueCPK as of Mark 080212, # since disp is reset from diTrueCPK to diDNACYLINDER by caller # [bruce comment 080213] # [note: there is a similar case in draw_bond_cyl and # old_writepov_bondcyl as of bruce 080213 povray bugfix] if bondcolor is None: # OK to use diBALL_bondcolor_prefs_key for now. Mark 2008-02-13. bondcolor = env.prefs.get(diBALL_bondcolor_prefs_key) drawcylinder(bondcolor, a1pos, a2pos, sigmabond_cyl_radius) elif disp == diTUBES: if shorten_tubes: # see Atom.howdraw for tubes; constant (0.9) might need adjusting #bruce 050726 changed that constant from 1.0 to 0.9 rad = TubeRadius * 1.1 * 0.9 # warning: if atom1 is a singlet, a1pos == center, so center - a1pos # is not good to use here. vec = norm(a2pos - a1pos) if atom1.element is not Singlet: a1pos = a1pos + vec * rad if atom2.element is not Singlet: a2pos = a2pos - vec * rad # note: this does not affect bandpos1, bandpos2 (which is good) ###e bruce 050513 future optim idea: when color1 == color2, draw just # one longer cylinder, then overdraw toolong indicator if needed. # Significant for big parts. BUT, why spend time on this when I # expect we'll do this drawing in C code before too long? if not toolong: # "not !=" is in case colors are Numeric arrays # (don't know if possible) if v1 and v2 and (not color1 != color2): #bruce 050516 optim: draw only one cylinder in this common case drawcylinder(color1, a1pos, a2pos, sigmabond_cyl_radius) else: if v1: drawcylinder(color1, a1pos, center, sigmabond_cyl_radius) if v2: drawcylinder(color2, center, a2pos, sigmabond_cyl_radius) #bruce 070921 bugfix: draw in consistent direction! This # affects alignment of cylinder cross section (a 13-gon) # around cylinder axis. Highlighted bond might differ # from regular bond in whether color1 != color2, so # without this fix, it can be slightly rotated, causing # part of the unhighlighted one to show through. if not (v1 and v2): drawsphere(black, center, sigmabond_cyl_radius, detailLevel) else: if highlighted: toolong_color = _default_toolong_hicolor ## not yet in prefs db else: toolong_color = env.prefs.get(bondStretchColor_prefs_key) drawcylinder(toolong_color, c1, c2, sigmabond_cyl_radius) if v1: drawcylinder(color1, a1pos, c1, sigmabond_cyl_radius) else: drawsphere(black, c1, sigmabond_cyl_radius, detailLevel) if v2: drawcylinder(color2, c2, a2pos, sigmabond_cyl_radius) #bruce 070921 bugfix: draw in consistent direction! # See comment above. else: drawsphere(black, c2, sigmabond_cyl_radius, detailLevel) if banding: drawcylinder(band_color, bandpos1, bandpos2, sigmabond_cyl_radius * 1.2) pass # maybe draw arrowhead showing bond direction [bruce 070415] # review: do we want this in diTrueCPK and/or diDNACYLINDER? # [bruce comment 080213] direction, is_directional = dir_info if (direction or is_directional) and (disp in (diBALL, diTUBES)): # If the bond has a direction, draw an arrowhead in the middle of the # bond-cylinder to show it. (Make that gray if this is ok, or red if # this is a non-directional bond.) If it has no direction but "wants # one" (is_directional), draw something to indicate that, not sure # what. ##e # # To fix a bug in highlighting of the arrowhead, use a1pos_not_shortened # and a2pos_not_shortened rather than a1pos and a2pos. Also split # draw_bond_cyl_arrowhead out of this code. [bruce 080121] draw_bond_cyl_arrowhead(a1pos_not_shortened, a2pos_not_shortened, direction, is_directional, color1, color2, sigmabond_cyl_radius) pass return # from draw_bond_cyl # == #bruce 080121 Split this out. def draw_bond_cyl_arrowhead(a1pos, a2pos, direction, # bond direction, relative to atom1 is_directional, color1, color2, sigmabond_cyl_radius): """ [private helper for draw_bond_cyl] Draw the bond-direction arrowhead for the bond cylinder with the given geometric/color/bond_direction parameters. Note that a1pos and a2pos should be the same for highlighted or unhighlighted drawing (even if they differ when the caller draws the main bond cylinder), or the arrowhead highlight might not properly align with its unhighlighted form. """ if direction < 0: a1pos, a2pos = a2pos, a1pos direction = - direction color1, color2 = color2, color1 error = direction and not is_directional if error: color = red else: color = color2 if direction == 0: # print "draw a confused/unknown direction somehow" # two orange arrows? no arrow? pass else: # draw arrowhead pointing from a1pos to a2pos, closer to a2pos. pos = a1pos axis = a2pos - a1pos drawrad = sigmabond_cyl_radius pts = [pos + t * axis for t in (0.6, 1.0)] # call drawcylinder with two radii for taper. # note: this is drawn by shader cylinders or as a polycone # depending on debug_prefs [bruce 090225 revision] drawcylinder(color, pts[0], pts[1], (drawrad * 2, 0)) return # == def writepov_bond(self, file, dispdef, col): """ Write this bond 'self' to a povray file (always using absolute coords, even for internal bonds). """ disp = max(self.atom1.display, self.atom2.display) if disp == diDEFAULT: disp = dispdef if disp < 0: disp = dispdef if disp in (diTrueCPK, diDNACYLINDER): # new feature, described in the other instance of this code. # warning: this code is duplicated in two places in this file. # [bruce 080212] if bond_draw_in_CPK(self): disp = diDNACYLINDER else: return if disp in (diLINES, diBALL, diTUBES, diDNACYLINDER): # (note: self is a bond.) povfile = writepov_to_file(file, col) detailLevel = 2 #k value probably has no effect glpane = None #k value probably has no effect highlighted = False draw_bond_main(self, glpane, disp, col, detailLevel, highlighted, povfile) return def old_writepov_bondcyl(atom1, atom2, disp, a1pos, c1, center, c2, a2pos, toolong, color1, color2, povfile, rad = None): """ [private function for this module, still used by new multicyl code 060622, once per cyl] Write one bond cylinder. atom args are only for checking rcovs vs DELTA. """ if disp == diLINES: if not toolong: povfile.line(a1pos, a2pos, color1) else: povfile.line(a1pos, center, color1) povfile.line(center, a2pos, color2) if disp == diBALL: bondColor = povfile.getBondColor() if not bondColor: bondColor = color1 povfile.bond(a1pos, a2pos, bondColor, rad) elif disp == diDNACYLINDER: # note: this case is also used for diTrueCPK as of Mark 080212, # since disp is reset from diTrueCPK to diDNACYLINDER by caller # [bruce comment 080213] # [note: there is a similar case in draw_bond_cyl and # old_writepov_bondcyl as of bruce 080213 povray bugfix] if 1: # bruce 080213 pure guesses about how best to do this in povray; # ideally we'd just clean up all this code to use the same # drawcylinder calling API in both povray and non-povray. bondColor = povfile.getBondColor() if not bondColor: bondColor = color1 povfile.bond(a1pos, a2pos, bondColor, rad) # .tube3 or .bond?? if disp == diTUBES: #Huaicai: If rcovalent is close to 0, like singlets, avoid 0 length # cylinder written to a pov file DELTA = 1.0E-5 isSingleCylinder = False if atom1.atomtype.rcovalent < DELTA: col = color2 isSingleCylinder = True if atom2.atomtype.rcovalent < DELTA: col = color1 isSingleCylinder = True if isSingleCylinder: povfile.tube3(a1pos, a2pos, col, rad) else: if not toolong: povfile.tube2(a1pos, color1, center, a2pos, color2, rad) else: povfile.tube1(a1pos, color1, c1, c2, a2pos, color2, rad) return # from old_writepov_bondcyl # end
NanoCAD-master
cad/src/graphics/model_drawing/bond_drawer.py
NanoCAD-master
cad/src/graphics/model_drawing/__init__.py
# Copyright 2008-2009 Nanorex, Inc. See LICENSE file for details. """ ExternalBondSetDrawer.py - can draw an ExternalBondSet, and keep drawing caches for it (e.g. display lists, perhaps for multiple drawing styles) @author: Bruce @version: $Id$ @copyright: 2008-2009 Nanorex, Inc. See LICENSE file for details. """ from graphics.model_drawing.TransformedDisplayListsDrawer import TransformedDisplayListsDrawer from graphics.drawing.ColorSorter import ColorSorter ##import foundation.env as env from utilities.debug import print_compact_traceback _DEBUG_DL_REMAKES = False # == class ExternalBondSetDrawer(TransformedDisplayListsDrawer): """ """ def __init__(self, ebset): # review: GL context not current now... could revise caller so it was TransformedDisplayListsDrawer.__init__(self) self._ebset = ebset # the ExternalBondSet we'll draw def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self._ebset) def destroy(self): """ remove cyclic refs, free display lists, etc """ self._ebset = None def _ok_to_deallocate_displist(self): #bruce 071103 """ Say whether it's ok to deallocate self's OpenGL display list right now (assuming our OpenGL context is current). [overrides TransformedDisplayListsDrawer method] """ return self._ebset.empty() # conservative -- maybe they're in a style that doesn't draw them -- # otoh, current code would still try to use a display list then # (once it supports DLs at all -- not yet as of 090213) def invalidate_display_lists_for_style(self, style): #bruce 090217 """ @see: documentation of same method in class Chunk [overrides superclass method] """ #### TODO: revise this when we can cache display lists even for # non-current display styles, to revise any cached style-including # display lists, whether or not that's the current style. # note: this is needed in principle, but might not be needed in # practice for the current calls. If it's slow, consider # a style-specific optim. [bruce 090217] c1, c2 = self._ebset.chunks if not self.glpane or \ c1.get_dispdef(self.glpane) == style or \ c2.get_dispdef(self.glpane) == style: self.invalidate_display_lists() return def draw(self, glpane, drawLevel, highlight_color): """ Draw all our bonds. Make them look selected if our ExternalBondSet says it should look selected (and if glpane._remake_display_lists is set). """ color = self._ebset.bondcolor() disp = self._ebset.get_dispdef(glpane) if 0: ## debug_pref: # initial testing stub -- just draw in immediate mode, in the same way # as if we were not being used. # modified from Chunk._draw_external_bonds: use_outer_colorsorter = True # not sure whether/why this is needed if highlight_color is not None: color = highlight_color # untested, also questionable cosmetically if use_outer_colorsorter: ColorSorter.start(glpane, None) for bond in self._ebset._bonds.itervalues(): bond.draw(glpane, disp, color, drawLevel) if use_outer_colorsorter: ColorSorter.finish(draw_now = True) return ### note: never calls superclass TransformedDisplayListsDrawer.draw, # as of before 090211 ### DUPLICATED CODE WARNING: # the following is similar in many ways to ChunkDrawer.draw. # See related comment there. # KLUGE: we'll use disp and color below, even though they come # from whichever of our chunks gets drawn first (i.e. occurs first # in Model Tree order). [After changing how we get them, bruce 090227, # that remains true -- it's just also true, now, even when we're # highlighted, fixing some bugs, except in rare cases where we were # never drawn unhighlighted.] The reasons are: # # - avoids changing current behavior about which chunk disp and color # gets used (changing that is desirable, but nontrivial to design # the intent); # # - not easy to recode things to draw bonds with half-colors # (though if disps differ, drawing it both ways would be easy). # # Note that we'd like to optim color changes, which is probably easy # in the DL case but not yet easy in the shader case, so nevermind that # for now. (Also disp changes, which would be easier.) # # We'd also like to use this method for highlighting; that's a separate # project which needs its own review; it might motivate us to revise # this, but probably not, since CSDL and DrawingSet draw methods # implement highlighting themselves, whether or not it's a solid color. # # [bruce 090217 comments & revisions] # first, return early if no need to draw self at all self.glpane = glpane # needed, for superclass displist deallocation ebset = self._ebset if ebset.empty(): print "fyi: should never happen: drawing when empty: %r" % self return chunks = ebset.chunks c1, c2 = chunks if c1.hidden and c2.hidden: return highlighted = highlight_color is not None # TODO: return if disp (from both chunks) doesn't draw bonds # and none of our bonds' atoms # have individual display styles set; for now, this situation will result # in our having an empty CSDL but drawing it # Note: frustum culling is done in our caller, # ChunkDrawer._draw_external_bonds, but only when its chunk # was culled. (It uses self._ebset.bounding_lozenge.) # So there is no need to do it here. # make sure self's CSDLs (display lists) are up to date, then draw them c1.basepos # for __getattr__ effect (precaution, no idea if needed) c2.basepos if not highlighted: self.track_use() ### REVIEW: need anything like glPushName(some glname) ? maybe one glname for the ebset itself? # guess: not needed: in DL case, bond glnames work, and in shader case, they work as colors, # implemented in the shaders themselves. #### TODO: glPushMatrix() etc, using matrix of chunk1. (here or in a subr) # Not needed until our coords are relative (when we optimize drag). elt_mat_prefs = glpane._general_appearance_change_indicator # Note: if we change how color and/or disp from our two chunks are combined # to determine our appearance, or if color of some bonds can be a combination # of color from both chunks, havelist_data might need revision. # For now, AFAIK, we draw with a single color and disp, so the following is # correct regardless of how they are determined (but the determination # ought to be stable to reduce undesirable color changes and DL remakes; # this was improved on 090227 re selection and highlighting). # See also the KLUGE comment above. [bruce 090217/090227] if color is not None: color = tuple(color) # be sure it's not a Numeric array (so we can avoid bug # for '==' without having to use same_vals) havelist_data = (disp, color, elt_mat_prefs) # note: havelist_data must be boolean true # note: in the following, the only difference from the chunk case is: # [comment not yet updated after changes of 090227] # missing: # - extra_displists # - some exception protection # different: # - c1.picked and c2.picked (two places) # - args to _draw_for_main_display_list # - comments # - some error message text # - maybe, disp and color draw_outside = [] # csdls to draw if self.havelist == havelist_data: # self.displist is still valid -- use it draw_outside += [self.displist] else: # self.displist needs to be remade (and then drawn, or also drawn) if _DEBUG_DL_REMAKES: print "remaking %r DL since %r -> %r" % \ (self, self.havelist, havelist_data) if not self.havelist: self._havelist_inval_counter += 1 # (probably not needed in this class, but needed in chunk, # so would be in common superclass draw method if we had that) self.havelist = 0 wantlist = glpane._remake_display_lists if wantlist: # print "Regenerating display list for %r (%d)" % \ # (self, env.redraw_counter) match_checking_code = self.begin_tracking_usage() ColorSorter.start(glpane, self.displist) # picked arg not needed since draw_now = False in finish # protect against exceptions while making display list, # or OpenGL will be left in an unusable state (due to the lack # of a matching glEndList) in which any subsequent glNewList is an # invalid operation. try: self._draw_for_main_display_list( glpane, disp, color, drawLevel, wantlist ) except: msg = "exception in ExternalBondSet._draw_for_main_display_list ignored" print_compact_traceback(msg + ": ") if wantlist: ColorSorter.finish(draw_now = False) draw_outside += [self.displist] self.end_tracking_usage( match_checking_code, self.invalidate_display_lists ) self.havelist = havelist_data # always set the self.havelist flag, even if exception happened, # so it doesn't keep happening with every redraw of this Chunk. #e (in future it might be safer to remake the display list to contain # only a known-safe thing, like a bbox and an indicator of the bug.) pass # note: if we ever have a local coordinate system, we may have it in # effect above but not below, like in ChunkDrawer; review at that time. for csdl in draw_outside: glpane.draw_csdl(csdl, selected = self._ebset.should_draw_as_picked(), # note: if not wantlist, this doesn't run, # so picked appearance won't happen # unless caller supplies it in color # (which is not equivalent) highlight_color = highlight_color) return def _draw_for_main_display_list(self, glpane, disp, color, drawLevel, wantlist): """ Draw graphics primitives into the display list (actually CSDL) set up by the caller. (For now, there is only one display list, which contains all our drawing under all conditions.) """ #bruce 090213, revised 090217 # todo: let caller pass (disp, color) pair for each chunk, # reorder atoms in each bond to correspond to that order # (easy if we always use chunk id sorting for that), # and draw things in a sensible way given both (disp, color) pairs. # This is mainly waiting for that "sensible way" to be designed. for bond in self._ebset._bonds.itervalues(): bond.draw(glpane, disp, color, drawLevel) return pass # end of class ExternalBondSetDrawer # end
NanoCAD-master
cad/src/graphics/model_drawing/ExternalBondSetDrawer.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ ChunkDrawer.py -- class ChunkDrawer, for drawing a chunk (using OpenGL or compatible primitives -- someday this may cover POV-Ray as well, but it doesn't as of early 2009) @author: Josh, Bruce, others @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. History: Written over several years as part of chunk.py. bruce 090123 split these methods out of class Chunk in chunk.py. (For prior svn history, see chunk.py. I decided against using svn copy, even though this code has lots of history in there, since it's shortly going to get refactored much more within this file, and things will be clearer if this split starts a clear separation of old and new in the history, especially since 3/4 of the old chunk.py is not this code.) bruce 090211 added markers where code was recently duplicated between self.draw and TransformedDisplayListsDrawer.draw (not yet used). This should be refactored soon into a common superclass, but first we need to bruce 090212 change mixin class into cooperating object ChunkDrawer bruce 090213 rename and move this module into graphics.model_drawing.ChunkDrawer TODO: refactor: * someday, use GraphicsRules, and make more than one instance per Chunk possible (supporting more than one view of a chunk, mixed display styles, and/or multiple cached display styles) """ from OpenGL.GL import glPushMatrix from OpenGL.GL import glPopMatrix from OpenGL.GL import glPushName from OpenGL.GL import glPopName from utilities.constants import diBALL from utilities.constants import diDNACYLINDER from utilities.constants import diLINES from utilities.constants import diTUBES from utilities.constants import diTrueCPK ##from utilities.constants import PickedColor from utilities.debug import print_compact_traceback from utilities.debug_prefs import debug_pref, Choice_boolean_True, Choice_boolean_False from utilities.GlobalPreferences import use_frustum_culling from utilities.Log import graymsg from utilities.prefs_constants import bondpointHotspotColor_prefs_key from utilities.prefs_constants import selectionColor_prefs_key import foundation.env as env from graphics.display_styles.displaymodes import get_display_mode_handler from graphics.drawing.ColorSorter import ColorSorter ##from drawer import drawlinelist from graphics.model_drawing.special_drawing import SPECIAL_DRAWING_STRAND_END from graphics.model_drawing.special_drawing import SpecialDrawing_ExtraChunkDisplayList from graphics.model_drawing.special_drawing import Chunk_SpecialDrawingHandler from graphics.model_drawing.TransformedDisplayListsDrawer import TransformedDisplayListsDrawer # == _DRAW_EXTERNAL_BONDS = True # Debug/test switch. # note: there is a similar constant _DRAW_BONDS in CS_workers.py. # == class ChunkDrawer(TransformedDisplayListsDrawer): """ Drawing class (meant only for use by class Chunk) """ #bruce 090211 renamed from Chunk_drawing_methods, revised from mixin # into cooperating class. The older mixin class in this file contained all # drawing-related methods for class Chunk which use # OpenGL drawing (or the same drawing primitives) # or which directly handle its OpenGL display lists. # Note: there are a few significant points of interaction between methods # and attrs in Chunk and ChunkDrawer. These can be found via their # interobject references: self._drawer in Chunk points to this object, # and self._chunk in this class points to its Chunk. That might be revised # if there can be more than one instance of this class per Chunk (though we # presume they all refer back to the chunk for its color and display # style settings). # Some of the methods/attrs that might want further refactoring include: # - haveradii, if it should be different for different displayed views # of one chunk, which seems likely; if we move it, we might move sel_radii # etc and findAtomUnderMouse too -- or maybe they belong in yet another # cooperating class?? # - findAtomUnderMouse is either specific to a glpane or needs one # (and a viewing ray, etc) passed in, though it's not a display/drawing # method but a picking/selection method. # - _havelist_inval_counter in this class, and Chunk _memo_dict, are only # used together (by whole-Chunk display styles (displaymodes.py), via new # methods in class Chunk). Further refactoring is desirable. # - self.glname is non-obvious, since it's possible that a chunk # has the same one even if displayed in more than one place -- or not, # if we want to use that to distinguish which copy is being hit. # Review this again when more refactoring is done. For now, it's in Chunk. _last_drawn_transform_value = (None, None) def __init__(self, chunk): """ """ TransformedDisplayListsDrawer.__init__(self) self._chunk = chunk return def getTransformControl(self): #bruce 090223 return self._chunk # == unsorted methods def invalidate_display_lists_for_style(self, style): #bruce 090211 """ @see: documentation of same method in class Chunk [overrides superclass method] """ #### TODO: revise this when chunks can cache display lists even for # non-current display styles, to revise any cached style-including # display lists, whether or not that's the current style. if not self.glpane or \ self._chunk.get_dispdef(self.glpane) == style: self.invalidate_display_lists() return #### REVIEW: all comments about track_inval, havelist, changeapp, # and whether the old code did indeed do changeapp and thus gl_update_something. def _ok_to_deallocate_displist(self): #bruce 071103 """ Say whether it's ok to deallocate self's OpenGL display list right now (assuming our OpenGL context is current). [overrides TransformedDisplayListsDrawer method] """ return len(self._chunk.atoms) == 0 # self.killed() might also be correct, # but would be redundant with this anyway def updateTransform(self): #bruce 090223 """ Tell all our CSDLs that their transform may have changed, so they should immediately get its new value and update their cached coordinates. """ if self._has_displist(): self.displist.updateTransform() for extra_displist in self.extra_displists.itervalues(): extra_displist.updateTransform() return # == drawing methods which are mostly specific to Chunk, though they have # == plenty of more general aspects which ought to be factored out def is_visible(self, glpane): """ Is self visible in the given glpane? Use a fast test; false positives are ok. """ center, radius = self._chunk.bounding_sphere() return glpane.is_sphere_visible( center, radius ) def _get_drawLevel(self, glpane): #bruce 090306 split out and optimized """ Get the sphere drawLevel (detail level) to use when drawing self. """ return glpane.get_drawLevel(self._chunk.assy) def draw(self, glpane, highlight_color = None): """ Draw self (including its external bonds, perhaps optimizing to avoid drawing them twice) in the appropriate display style, based on the style assigned to self's individual atoms (if there is one), or to self, or to glpane. This draws everything associated with self or its atoms or bonds, including atom-selection indicators, atom overlap indicators, error indicators, self's appearance as selected or not, bond letters, base letters, etc. Most but not all of what we draw is included in one or more display lists, which are updated as needed before drawing them. The output of this method consists of side effects, namely OpenGL calls (which are not in general suitable for inclusion in a display list being compiled by the caller). The correct GL context must be current whenever this method is called. @param highlight_color: if passed (and not None), draw self in highlighted form using the given highlight_color, with some details changed about exactly what we draw and how. """ #bruce 090212 revised docstring #bruce 090225 added highlight_color option, so I can rewrite # draw_highlighted as a call to this method. highlighted = (highlight_color is not None) hidden = self._chunk.hidden and not highlighted # REVIEW: is this wise, compared to just self._chunk.hidden? # It affects the code below, since it means displists might # need remaking even when highlighted. [bruce 090225 comment] # review: # - is glpane argument used, aside from setting self.glpane? [yes.] # - is self.glpane used in this method (after we set it initially)? # [yes, at least in a submethod.] # - (regarding self.glpane uses after this method returns, see below.) # - is any other way of finding the glpane used? # someday, clean up everything related to the glpane arg and self.glpane # (or effectively supersede them by using GraphicsRules). self.glpane = glpane # needed, see below ### review (not urgent): during this method, or after it returns, # is self.glpane needed here or in self._chunk or both? [bruce 090212] # # known reasons self.glpane might be needed in one or the other class: # - for the edit method - Mark [2004-10-13] # - in BorrowerChunk._dispfunc, called by draw_dispdef [bruce 060411] # - in invalidate_display_lists_for_style [bruce 090212] # - by self.call_when_glcontext_is_next_current via self._gl_context_if_any # - for delegate_draw_chunk, see code below # - in Chunk.changeapp [removed as of bruce 090212] # note: the old comment about that use said: #bruce 050804: self.glpane is now also used in self.changeapp(), # since it's faster than self.track_inval (whose features are overkill for this), # though the fact that only one glpane can be recorded in self # is a limitation we'll need to remove at some point. # but now I'm revising that (in self.invalidate_display_lists) to use # track_inval, not direct gl_update (or related method), since # that's theoretically better. (So it's no longer a use of # self.glpane.) If it's too slow (which I doubt), we'll notice it # in a profile and optimize it. if not self._chunk.atoms: return # Indicate overlapping atoms, if that pref is enabled. # We do this outside of the display list so we can still use that # for most of the drawing (for speed). We do it even for atoms # in hidden chunks, even in display modes that don't draw atoms, # etc. (But not for frustum culled atoms, since the indicators # would also be off-screen.) [bruce 080411 new feature] drawing_frame = self.get_part_drawing_frame() indicate_overlapping_atoms = drawing_frame and \ drawing_frame.indicate_overlapping_atoms # note: using self._chunk.part for this is a slight kluge; # see the comments where this variable is defined in class Part. # review: is there any problem with this when highlighted? if hidden and not indicate_overlapping_atoms: # (usually do this now, to avoid overhead of frustum test; # if indicate_overlapping_atoms is true, we'll test # hidden again below, to make sure we still # skip other drawing) return # Frustum culling test [piotr 080331] # Don't return yet on failure, because external bonds # may be still drawn [piotr 080401] is_chunk_visible = self.is_visible(glpane) if indicate_overlapping_atoms and is_chunk_visible: self.draw_overlap_indicators_if_needed() # todo: pass highlight_color. # todo: make this work with 'reuse cached drawingsets' debug_pref. # That will require calling a variant of collect_drawing_function # which works in absolute model coordinates. (Adding that is # straightforward -- see comment in our superclass which defines # that method.) [bruce 090312 comment] pass if hidden: # catch the case where indicate_overlapping_atoms skipped this test earlier # (don't return just from not is_chunk_visible, due to external bonds) return # note: if highlighted and self._chunk.hidden, but (not hidden) # (which is possible due to definition of hidden above), # then we might draw self for the first time # after a move, in highlighted form. That means we need all the # same logic for possibly remaking our display lists as if # not highlighted. If this proves problematic, we can condition # that logic on not highlighted, but only if we also define hidden # as self._chunk.hidden when highlighted. [bruce 090225 comment] self._chunk.basepos # note: has side effects in __getattr__ # make sure basepos is up-to-date, so basecenter is not changed # during the redraw. #e Ideally we'd have a way to detect or # prevent further changes to it during redraw, but this is not # needed for now since they should not be possible, and should # cause visible bugs if they happen. At least let's verify the # self._chunk coord system has not changed by the time we're done # (btw, copying quat.vec rather than quat is an optim, bruce 090306): current_transform_value = ( + self._chunk.basecenter, + self._chunk.quat.vec ) # see comment below for why we have to compare the pieces, not the whole if current_transform_value[0] != self._last_drawn_transform_value[0] or \ current_transform_value[1] != self._last_drawn_transform_value[1] : # Our local coordinate system (aka our transform, stored in # self._chunk) has changed since we were last drawn. Before # drawing any CSDLs whose tranformControl is self._chunk (i.e. # any of our CSDLs), we need to make sure they update their # internal coordinates based on the new value of our transform. ### TODO: optimize this to not be redundant with the one called by # ColorSorter.finish for any of those CSDLs we are about to remake. # (Not trivial. If CSDLs updated lazily, they'd need to know which # DrawingSets contained them, adding complexity. So we'd need to # track this here instead, or in a "needs update" flag on CSDLs # which we or something else checks on all the ones we'll draw at # the end. I don't know whether redundant update is common, so I # don't know whether that's worthwhile. Note that this update needs # to cover extra_displists now, and ExternalBondSets in the # future.) [bruce 090226 comment] self.updateTransform() pass self._last_drawn_transform_value = current_transform_value ### WARNING: DUPLICATED CODE: much of the remaining code in this method # is very similar to ExternalBondSetDrawer.draw. Ideally the common # parts would be moved into our common superclass, # TransformedDisplayListsDrawer. [bruce 090211/090217 comment] #bruce 050804 (probably not needed at that time due to glpane code # in changeapp) / 090212 (probably needed now): # call track_use to tell whatever is now drawing us # (presumably our arg, glpane, but we don't assume this right here) # how to find out when any of our display list contents next become # invalid, so it can know it needs to redraw us. [note: I didn't check # whether extra_displist invalidity is handled by this same code (guess: # no), or in some independent way using gl_update.] if not highlighted: # (### review the logic of this condition sometime) self.track_use() drawLevel = self._get_drawLevel(glpane) disp = self._chunk.get_dispdef(glpane) if is_chunk_visible: do_outside_local_coords = [] # temporary kluge, won't be needed once we always use DrawingSets # piotr 080401: If the chunk is culled, skip drawing, but still draw # external bonds (unless a separate debug pref is set.) # The frustum culling test is now performed individually for every # external bond. #This is needed for chunk highlighting ### REVIEW: this is our first use of "nested glnames". The hover # highlighting code in GLPane was written with the assumption # that we never use them, and the effects of using them on it # have not been reviewed. Conceivably it might slow it down # (by making some of its optims work less well, e.g. due to # overlapping highlight regions between self and its draw-children # with their own glnames (atoms and bonds), or cause bugs, though # I think both of those are unlikely, so this review is not urgent. # [bruce 080411 comment] glPushName(self._chunk.glname) # doesn't matter when highlighted # put it in its place # (note: this still matters even though we use transformControls in # our CSDLs, when wantlist (computed below) is False, and probably # for other drawing not in CSDLs (not fully analyzed whether there # is any). [bruce 090224 comment]) glPushMatrix() self.begin_collecting_drawing_funcs() # call this sometime before the first possible # call of collect_drawing_func try: # do our popMatrix no matter what self._chunk.applyMatrix(glpane) ##delegate_selection_wireframe = False delegate_draw_atoms = False delegate_draw_chunk = False # look for a display mode handler for this chunk # (whether it's a whole-chunk mode, or one we'll pass to the # atoms as we draw them (nim)) [bruce 060608] hd = get_display_mode_handler(disp) # see if it's a chunk-only handler. If so, we don't draw # atoms or chunk selection wireframe ourselves -- instead, # we delegate those tasks to it. if hd: chunk_only = hd.chunk_only ##delegate_selection_wireframe = chunk_only delegate_draw_atoms = chunk_only delegate_draw_chunk = chunk_only #e maybe later, we'll let hd tell us each of these, # based on the chunk state. pass #bruce 060608 moved drawing of selection wireframe from here to # after the new increment of _havelist_inval_counter # (and split it into a new submethod), even though it's done # outside of the display list. This was necessary for # _f_drawchunk_selection_frame's use of memoized data to work. ## self._draw_selection_frame(glpane, delegate_selection_wireframe, hd) # cache chunk display (other than selection wireframe or hover # highlighting) as OpenGL display list # [bruce 050415 changed value of self.havelist when it's not 0, # from 1 to (disp,), # to fix bug 452 item 15 (no havelist inval for non-current # parts when global default display mode is changed); this # will incidentally optimize some related behaviors by avoiding # some needless havelist invals, now that we've also removed # the now-unneeded changeapp of all chunks upon global dispdef # change (in GLPane.setGlobalDisplayStyle).] # [bruce 050419 also including something for element radius and # color prefs, to fix bugs in updating display when those # change (eg bug 452 items 12-A, 12-B).] elt_mat_prefs = glpane._general_appearance_change_indicator havelist_data = (disp, elt_mat_prefs) # note: havelist_data must be boolean true wantlist = glpane._remake_display_lists #bruce 090224 # We'll only remake invalid displists when this is true; # otherwise we'll just draw their desired contents directly, # without remaking any CSDLs. # # Specifically: When the following code decides to remake # and draw, or just draw, a CSDL, it behaves differently # depending on this flag. # # If wantlist is true (usual case), remakes and draws are # separated (in some cases by passing draw_now = False to # various draw-like methods), so drawing can be done later, # outside of local coords, since CSDL.transformControl would # be redundant with them, and since it might be deferred # even more (into a DrawingSet we merely maintain in this # method, by calling glpane.draw_csdl). # # If wantlist is False, remakes won't happen and drawing # will be done immediately, within GL state that reproduces # the desired local coordinates (current now, set up above # by applyMatrix). (In the future we might not even set up # that GL state except when wantlist is false, as an optim.) ### POSSIBLE BUG: chunk highlighting when not wantlist; # see comment in draw_highlighted. draw_outside = [] # csdls to draw outside local coords if self.havelist == havelist_data: # self.displist is still valid -- just draw it (regardless # of wantlist). This is done below, outside local coords, # since they would be redundant with use of # self.displist.transformControl. Note that some extra # displists may still need remaking -- this is handled # separately below. draw_outside += [self.displist] pass else: # our main display list (and all extra lists) needs to be remade #bruce 060608: record info to help per-chunk display modes # figure out whether they need to invalidate their memo data. if not self.havelist: # Only count when it was set to 0 externally, not # just when it doesn't match and we reset it # below. (Note: current code will also increment # this every frame, when wantlist is false. I'm # not sure what to do about that. Could we set it # here to False rather than 0, so we can tell?? # ##e) self._havelist_inval_counter += 1 ##e in future we might also record eltprefs, matprefs, ##drawLevel (since they're stored in .havelist) self.havelist = 0 #bruce 051209: this is now needed self.extra_displists = {} # we'll make new ones as needed if wantlist: ##print "Regenerating display list for %s" % self.name match_checking_code = self.begin_tracking_usage() ColorSorter.start(glpane, self.displist) # Note: passing self._chunk.picked was needed # when ColorSorter.finish (below) got # draw_now = True, but is not needed now # since it's passed when drawing self.displist. # (This cleanup is part of deprecating CSDL picked state.) # [bruce 090219] # Protect against exceptions while making display # list, or OpenGL will be left in an unusable state (due to the lack # of a matching glEndList) in which any subsequent glNewList is an # invalid operation. [bruce 041028] # Note: if not wantlist, this does immediate drawing # (and never creates extra_displists, due to logic inside # _draw_for_main_display_list). # The transformControl is not used, but we got the same effect # by a pushMatrix/applyMatrix above. [bruce 090224 comment] try: self._draw_for_main_display_list( glpane, disp, (hd, delegate_draw_atoms, delegate_draw_chunk), wantlist) except: msg = "exception in Chunk._draw_for_main_display_list ignored" print_compact_traceback(msg + ": ") if wantlist: ColorSorter.finish(draw_now = False) # args when highlighted don't need to differ, # since not drawing now draw_outside += [self.displist] self.end_tracking_usage( match_checking_code, self.invalidate_display_lists ) self.havelist = havelist_data # we always set self.havelist, even if an exception # happened, so it doesn't keep happening with every # redraw of this Chunk. (Someday: it might be better # to remake the display list to contain only a # known-safe thing, like a bbox and an indicator of # the bug.) pass # end of "remake self.displist" case # we still need to draw_outside below, but first, # remake and/or draw each extra displist. This can be done in # the same way whether or not we just remade self.displist, # since if we did, they all need remaking, and if we didn't, # perhaps some of them need remaking anyway, and in either # case, the ones that need it know this. The only issue is # the effect of wantlist if the main list was valid but # the extra lists need remaking, but it should be the case # that passing wantlist = False to their "remake and draw" # can still correctly draw them without remaking them, # and the coordinate system vs transformControl issues # should be the same. (If not wantlist but self.displist is # not valid, it's simpler, since we won't make any # extra_displists then (I think), but we can't take # advantage of that due to the other case described.) # [bruce 090224] # draw the extra_displists, remaking as needed if wantlist for extra_displist in self.extra_displists.itervalues(): extra_displist.draw_but_first_recompile_if_needed( glpane, selected = self._chunk.picked, wantlist = wantlist, draw_now = not wantlist ) if wantlist: draw_outside += [extra_displist.csdl] continue # REVIEW: is it ok that self._chunk.glname is exposed for the following # _renderOverlayText drawing? Guess: yes, even though it means mouseover # of the text will cause a redraw, and access to chunk context menu. # If it turns out that that redraw also visually highlights the chunk, # we might reconsider, but even that might be ok. # [bruce 081211 comments] if ( self._chunk.chunkHasOverlayText and self._chunk.showOverlayText ): self._renderOverlayText(glpane) # review args when highlighted #@@ninad 070219 disabling the following-- ## self._draw_selection_frame(glpane, delegate_selection_wireframe, hd) # piotr 080320; bruce 090312 revised if hd: self.collect_drawing_func( hd._f_drawchunk_realtime, glpane, self._chunk, highlighted = highlighted ) pass if self._chunk.hotspot is not None: # note: accessing self._chunk.hotspot can have side effects in getattr self.overdraw_hotspot(glpane, disp) ### REVIEW args when highlighted # note: this only does anything for pastables # (toplevel clipboard items) as of 050316 # Make sure our transform value didn't change during draw # (serious bug if so -- it would make display list coordinate # system ambiguous). [Note: always use !=, not ==, to compare # Numeric arrays, and never compare tuples containing them # (except with same_vals), to avoid bugs. See same_vals # docstring for details.] if ( current_transform_value[0] != self._chunk.basecenter or current_transform_value[1] != self._chunk.quat.vec ): assert 0, \ "bug: %r transform changed during draw, from %r to %r" % \ ( self._chunk, current_transform_value, ( self._chunk.basecenter, self._chunk.quat.vec ) ) pass pass # end of drawing within self's local coordinate frame except: print_compact_traceback("exception in Chunk.draw, continuing: ") self._chunk.popMatrix(glpane) # some csdl-drawing has to be done here, not above, since the # transformControls they contain would be redundant with the # local coords (in GL matrix state) we were in above. (The # local coords in GL state wouldn't be needed if we eliminated # "wantlist = false" and always use DrawingSets -- except for # some other, non-CSDL drawing also done above.) # This also helps us pass all drawn CSDLs to draw_csdl, # to support DrawingSets. [bruce 090224] # (todo: exception protection for this, too?) for csdl in draw_outside: # csdl is always a real CSDL # (since for an extra_displist we added extra_displist.csdl # to this list) glpane.draw_csdl(csdl, selected = self._chunk.picked, highlight_color = highlight_color) self.end_collecting_drawing_funcs(glpane) # before glPopName glPopName() # pops self._chunk.glname pass # end of 'if is_chunk_visible:' self._draw_outside_local_coords(glpane, disp, drawLevel, is_chunk_visible, highlight_color ) return # from Chunk.draw() def _renderOverlayText(self, glpane): # by EricM gotone = False for atom in self._chunk.atoms.itervalues(): text = atom.overlayText if (text): gotone = True pos = atom.baseposn() radius = atom.drawing_radius() * 1.01 pos = pos + glpane.out * radius glpane.renderTextAtPosition(pos, text) if (not gotone): self._chunk.chunkHasOverlayText = False def _draw_outside_local_coords(self, glpane, disp, drawLevel, is_chunk_visible, highlight_color ): """ Do the part of self.draw that goes outside self's local coordinate system and outside its display lists. [Subclasses can extend this if needed] """ #bruce 080520 split this out; extended in class VirtualSiteChunkDrawer draw_external_bonds = True # piotr 080401 # Added for the additional test - the external bonds could be still # visible even if the chunk is culled. # For extra performance, the user may skip drawing external bonds # entirely if the frustum culling is enabled. This may have some side # effects: problems in highlighting external bonds or missing # external bonds if both chunks are culled. piotr 080402 if debug_pref("GLPane: skip all external bonds for culled chunks", Choice_boolean_False, non_debug = True, prefs_key = True): # the debug pref has to be checked first if not is_chunk_visible: # the chunk is culled piotr 080401 # so don't draw external bonds at all draw_external_bonds = False # draw external bonds. # Could we skip this if display mode "disp" never draws bonds? # No -- individual atoms might override that display mode. # Someday we might decide to record whether that's true when # recomputing externs, and to invalidate it as needed -- since it's # rare for atoms to override display modes. Or we might even keep a # list of all our atoms which override our display mode. ###e # [bruce 050513 comment] if draw_external_bonds and self._chunk.externs: self._draw_external_bonds(glpane, disp, drawLevel, is_chunk_visible, highlight_color ) return # from Chunk._draw_outside_local_coords() def _draw_external_bonds(self, glpane, disp, drawLevel, is_chunk_visible, highlight_color ): """ Draw self's external bonds (if debug_prefs and frustum culling permit). @note: handles both cases of debug_pref for whether to use ExternalBondSets for drawing them. """ if not _DRAW_EXTERNAL_BONDS: return #bruce 080215 split this out, added one debug_pref # decide whether to draw any external bonds at all # (possible optim: decide once per redraw, cache in glpane) # piotr 080320: if this debug_pref is set, the external bonds # are hidden whenever the mouse is dragged. This speeds up interactive # manipulation of DNA segments by a factor of 3-4x in tubes # or ball-and-sticks display styles. # This extends the previous condition to suppress the external # bonds during animation. suppress_external_bonds = ( (getattr(glpane, 'in_drag', False) # glpane.in_drag undefined in ThumbView and debug_pref("GLPane: suppress external bonds when dragging?", Choice_boolean_False, non_debug = True, prefs_key = True )) or (self._chunk.assy.o.is_animating # review: test in self._chunk.assy.o or glpane? and debug_pref("GLPane: suppress external bonds when animating?", Choice_boolean_False, non_debug = True, prefs_key = True )) ) if suppress_external_bonds: # review: and not highlighted? return # external bonds will be drawn (though some might be culled). # make sure the info needed to draw them is up to date. self._chunk._update_bonded_chunks() # decide whether external bonds should be frustum-culled. frustum_culling_for_external_bonds = \ not is_chunk_visible and use_frustum_culling() # piotr 080401: Added the 'is_chunk_visible' parameter default to True # to indicate if the chunk is culled or not. Assume that if the chunk # is not culled, we have to draw the external bonds anyway. # Otherwise, there is a significant performance hit for frustum # testing the visible bonds. # find or set up repeated_bonds_dict # Note: to prevent objects (either external bonds themselves, # or ExternalBondSet objects) from being drawn twice, # [new feature, bruce 070928 bugfix and optimization] # we use a dict recreated each time their part gets drawn, # in case of multiple views of the same part in one glpane; # ideally the draw methods would be passed a "model-draw-frame" # instance (associated with the part) to make this clearer. # If we can ever draw one chunk more than once when drawing one part, # we'll need to modify this scheme, e.g. by optionally passing # that kind of object -- in general, a "drawing environment" # which might differ on each draw call of the same object.) # update, bruce 090218: revised drawing_frame code below; # this fixes some but not all of the future problems mentioned above. drawing_frame = self.get_part_drawing_frame() # might be None, in theory repeated_bonds_dict = drawing_frame and drawing_frame.repeated_bonds_dict # might be None, if we're not being drawn between a pair # of calls to part.before/after_drawing_model # (which is deprecated but might still occur), # or if our chunk has no Part (a bug). if repeated_bonds_dict is None: # (Note: we can't just test "not repeated_bonds_dict", # in case it's {}.) # This can happen when chunks are drawn in other ways than # via Part.draw (e.g. as Extrude repeat units?), # or [as revised 080314] due to bugs in which self._chunk.part # is None; we need a better fix for this, but for now, # just don't use the dict. As a kluge to avoid messing up # the loop below, just use a junk dict instead. # [bruce 070928 fix new bug 2548] repeated_bonds_dict = {} # kluge if debug_pref("GLPane: use ExternalBondSets for drawing?", #bruce 080707 Choice_boolean_True, # changed to default True, bruce 090217, # though not yet fully tested non_debug = True, prefs_key = "v1.2/use ExternalBondSets for drawing?" ): # draw ExternalBondSets objects_to_draw = self._chunk._bonded_chunks.itervalues() objects_are_ExternalBondSets = True use_outer_colorsorter = False selColor = bondcolor = None # not used in this case (nor is disp) else: # draw Bonds (not using display lists; no longer happens by default) objects_to_draw = self._chunk.externs objects_are_ExternalBondSets = False use_outer_colorsorter = True bondcolor = self._chunk.drawing_color() # Note: this choice of bondcolor is flawed, because it depends # on which chunk is drawn first of the two that are connected. # I'm leaving this behavior in place, but revising how it works # in the two cases of which kind of object we draw. # [bruce 090227] selColor = self._chunk.picked and env.prefs[selectionColor_prefs_key] # kluge optim of tracked usage: we happen to know # that selColor can only be used if self._chunk.picked; # this depends on implementation of Bond.should_draw_as_picked # actually draw them if use_outer_colorsorter: # note: not used with ExternalBondSets ColorSorter.start(glpane, None) # [why is this needed? bruce 080707 question] for bond in objects_to_draw: # note: bond might be a Bond, or an ExternalBondSet if id(bond) not in repeated_bonds_dict: # BUG: disp and bondcolor (whether computed here or in EBSet) # depend on self, so the bond appearance may depend on which # chunk draws it first (i.e. on their Model Tree order). # How to fix this is the subject of a current design discussion. # (Even after bruce 090227, since only the implem changed then.) # [bruce 070928 comment] repeated_bonds_dict[id(bond)] = bond if frustum_culling_for_external_bonds: # bond frustum culling test piotr 080401 ### REVIEW: efficient under all settings of debug_prefs?? # [bruce 080702 question] c1, c2, radius = bond.bounding_lozenge() if not glpane.is_lozenge_visible(c1, c2, radius): continue # skip the bond drawing if culled if objects_are_ExternalBondSets: # bond is an ExternalBondSet; it will test # should_draw_as_picked internally # (in a better way than just color = selColor), # and also determine disp and bondcolor internally. # Note that varying color passed here in place of bondcolor # would cause this ExternalBondSet to remake its display # lists, which would slow down redraw after chunk selection # changes, so don't do it. [bruce 080702] bond.draw(glpane, self._chunk, drawLevel, highlight_color = highlight_color) else: # bond is a Bond if bond.should_draw_as_picked(): # note, this can differ for different bonds, # since they connect to different chunks besides self color = selColor #bruce 080430 cosmetic improvement else: color = bondcolor bond.draw(glpane, disp, color, drawLevel) continue if use_outer_colorsorter: ColorSorter.finish(draw_now = True) return # from _draw_external_bonds ## def _draw_selection_frame(self, glpane, delegate_selection_wireframe, hd): ## "[private submethod of self.draw]" ## chunk = self._chunk ## if chunk.picked: ## if not delegate_selection_wireframe: ## try: ## drawlinelist(PickedColor, chunk.polyhedron or []) ## except: ## # bruce 041119 debug code; ## # also "or []" failsafe (above) ## # in case recompute exception makes it None ## print_compact_traceback("exception in drawlinelist: ") ## print "(chunk.polyhedron is %r)" % chunk.polyhedron ## else: ## hd._f_drawchunk_selection_frame(glpane, chunk, PickedColor, highlighted = False) ## pass ## return def get_part_drawing_frame(self): #bruce 090218 """ Return the current Part_drawing_frame if we can find one, or None. @see: class Part_drawing_frame """ # note: accessing part.drawing_frame allocates it on demand # if it wasn't already allocated during that call of Part.draw. #### REVIEW: drawing_frame is probably the misnamed, # now that it's not the same as GLPane.csdl_collector; # see related docstrings in Part or its helper class for this attr # for better description, explaining when we'd use more than # one per frame in the future. Maybe part_drawing_frame would be # a better name?? [bruce 090219 comment] return self._chunk.part and self._chunk.part.drawing_frame def draw_overlap_indicators_if_needed(self): #bruce 080411, renamed 090108 """ If self overlaps any atoms (in self's chunk or in other chunks) already scanned (by calling this method on them) during this drawing frame (paintGL call), draw overlap indicators around self and/or those atoms as needed, so that each atom needing an overlap indicator gets one drawn at least once, assuming this method is called on all atoms drawn during this drawing frame. """ model_draw_frame = self.get_part_drawing_frame() if not model_draw_frame: return neighborhoodGenerator = model_draw_frame._f_state_for_indicate_overlapping_atoms if not neighborhoodGenerator: # precaution after refactoring, probably can't happen [bruce 090218] return for atom in self._chunk.atoms.itervalues(): pos = atom.posn() prior_atoms_too_close = neighborhoodGenerator.region(pos) if prior_atoms_too_close: # This atom overlaps the prior atoms. # Draw an indicator around it, # and around the prior ones if they don't have one yet. # (That can be true even if there is more than one of them, # if the prior ones were not too close to each other, # so for now, just draw it on the prior ones too, even # though this means drawing it twice for each atom.) # # Pass an arg which indicates the atoms for which one or more # was too close. See draw_overlap_indicator docstring for more # about how that can be used, given our semi-symmetrical calls. for prior_atom in prior_atoms_too_close: prior_atom.draw_overlap_indicator((atom,)) atom.draw_overlap_indicator(prior_atoms_too_close) neighborhoodGenerator.add(atom) continue return def _draw_for_main_display_list(self, glpane, disp0, hd_info, wantlist): """ [private submethod of self.draw] Draw the contents of our main display list, which the caller has already opened for compile and execute (or the equivalent, if it's a ColorSortedDisplayList object) if wantlist is true, or doesn't want to open otherwise (so we do immediate mode drawing then). Also (if self attrs permit and wantlist argument is true) capture functions for deferred drawing into new instances of appropriate subclasses of ExtraChunkDisplayList added to self.extra_displists, so that some aspects of our atoms and bonds can be drawn from separate display lists, to avoid remaking our main one whenever those need to change. """ if wantlist and \ hasattr(glpane, 'graphicsMode') and \ debug_pref("use special_drawing_handlers?", Choice_boolean_True, #bruce 080606 enable by default for v1.1 non_debug = True, # (but leave it visible in case of bugs) prefs_key = True): # set up the right kind of special_drawing_handler for self; # this will be passed to the draw calls of our atoms and bonds # [new feature, bruce 080605] # # bugfix [bruce 080606 required for v1.1, for dna in partlib view]: # hasattr test, since ThumbView has no graphicsMode. # (It ought to, but that's a refactoring too big for this release, # and giving it a fake one just good enough for this purpose doesn't # seem safe enough.) ### REVIEW: can/should we optim this by doing it during __init__? special_drawing_classes = { # todo: move into a class constant SPECIAL_DRAWING_STRAND_END: SpecialDrawing_ExtraChunkDisplayList, } self.special_drawing_handler = \ Chunk_SpecialDrawingHandler( self, special_drawing_classes ) else: self.special_drawing_handler = None del wantlist #bruce 050513 optimizing this somewhat; 060608 revising it if debug_pref("GLPane: report remaking of chunk display lists?", Choice_boolean_False, non_debug = True, prefs_key = True ): #bruce 080214 print "debug fyi: remaking display lists for chunk %r" % self summary_format = graymsg( "debug fyi: remade display lists for [N] chunk(s)" ) env.history.deferred_summary_message(summary_format) hd, delegate_draw_atoms, delegate_draw_chunk = hd_info # draw something for the chunk as a whole if delegate_draw_chunk: hd._f_drawchunk(self.glpane, self._chunk) else: self._standard_draw_chunk(glpane, disp0) # draw the individual atoms and internal bonds (if desired) if delegate_draw_atoms: pass # nothing for this is implemented, or yet needed [as of bruce 060608] else: self._standard_draw_atoms(glpane, disp0) return def draw_highlighted(self, glpane, color): """ Draw self._chunk as highlighted with the specified color. @param glpane: the GLPane @param color: highlight color (must not be None) @see: dna_model.DnaGroup.draw_highlighted @see: SelectChunks_GraphicsMode.drawHighlightedChunk() @see: SelectChunks_GraphicsMode._get_objects_to_highlight() """ #This was originally a sub-method in #SelectChunks_GraphicsMode.drawHighlightedChunks. Moved here #(Chunk.draw_highlighted) on 2008-02-26 [by Ninad] # In future, 'draw_in_abs_coords' defined on some node classes # could be merged into this method (for highlighting various objects). # [heavily revised by bruce 090225] assert color is not None wantlist = glpane._remake_display_lists if not wantlist: # not worth highlighting if valid csdls not available # [bruce 090225 revision; #REVIEW: do inside .draw?] return self.draw(glpane, highlight_color = color) return def _standard_draw_chunk(self, glpane, disp0, highlighted = False): """ [private submethod of self.draw] Draw the standard representation of this chunk as a whole (except for chunk selection wireframe), as if self's display mode was disp0 (not a whole-chunk display mode). This is run inside our local coordinate system and display-list-making. It is not run if chunk drawing is delegated to a whole-chunk display mode. @note: as of 080605 or before, this is always a noop, but is kept around since it might be used someday (see code comments) """ # note: we're keeping this for future expansion even though it's # always a noop at the moment (even in subclasses). # It's not used for whole-chunk display styles, but it might be used # someday, e.g. to let chunks show their axes, name, bbox, etc, # or possibly to help implement a low-level-of-detail form. # [bruce 090113 comment] del glpane, disp0, highlighted return def _standard_draw_atoms(self, glpane, disp0): """ [private submethod of self.draw:] Draw all our atoms and all their internal bonds, in the standard way, *including* atom selection wireframes, as if self's display mode was disp0; this occurs inside our local coordinate system and display-list-making; it doesn't occur if atom drawing is delegated to our display mode. """ #bruce 060608 split this out of _draw_for_main_display_list drawLevel = self._get_drawLevel(glpane) drawn = {} # bruce 041014 hack for extrude -- use _colorfunc if present # [part 1; optimized 050513] _colorfunc = self._chunk._colorfunc # might be None # [as of 050524 we supply a default so it's always there] _dispfunc = self._chunk._dispfunc #bruce 060411 hack for BorrowerChunk, might be more generally useful someday atomcolor = self._chunk.drawing_color() # None or a color # bruce 080210 bugfix (predicted) [part 1 of 2]: # use this even when _colorfunc is being used # (so chunk colors work in Extrude; IIRC there was a bug report on that) # [UNTESTED whether that bug exists and whether this fixes it] bondcolor = atomcolor # never changed below for atom in self._chunk.atoms.itervalues(): #bruce 050513 using itervalues here (probably safe, speed is needed) try: color = atomcolor # might be modified before use disp = disp0 # might be modified before use # bruce 041014 hack for extrude -- use _colorfunc if present # [part 2; optimized 050513] if _colorfunc is not None: try: color = _colorfunc(atom) # None or a color except: print_compact_traceback("bug in _colorfunc for %r and %r: " % (self, atom)) _colorfunc = None # report the error only once per displist-redraw color = None else: if color is None: color = atomcolor # bruce 080210 bugfix (predicted) [part 2 of 2] #bruce 060411 hack for BorrowerChunk; done here and # in this way in order to not make ordinary drawing # inefficient, and to avoid duplicating this entire method: if _dispfunc is not None: try: disp = _dispfunc(atom) except: print_compact_traceback("bug in _dispfunc for %r and %r: " % (self, atom)) _dispfunc = None # report the error only once per displist-redraw disp = disp0 # probably not needed pass pass pass pass # otherwise color and disp remain unchanged # end bruce hack 041014, except for use of color rather than # self.color in Atom.draw (but not in Bond.draw -- good??) atomdisp = atom.draw( glpane, disp, color, drawLevel, special_drawing_handler = self.special_drawing_handler ) #bruce 050513 optim: if self and atom display modes don't need to draw bonds, # we can skip drawing bonds here without checking whether their other atoms # have their own display modes and want to draw them, # since we'll notice that when we get to those other atoms # (whether in self or some other chunk). # (We could ask atom.draw to return a flag saying whether to draw its bonds here.) # To make this safe, we'd need to not recompute externs here, # but that should be ok since they're computed separately anyway now. # So I'm removing that now, and doing this optim. ###e (I might need to specialcase it for singlets so their # bond-valence number is still drawn...) [bruce 050513] #bruce 080212: this optim got a lot less effective since a few CPK bonds # are now also drawn (though most are not). if atomdisp in (diBALL, diLINES, diTUBES, diTrueCPK, diDNACYLINDER): # todo: move this tuple into bonds module or Bond class for bond in atom.bonds: if id(bond) not in drawn: if bond.atom1.molecule is not self._chunk or \ bond.atom2.molecule is not self._chunk: # external bond (todo: could simplify the test) pass else: # internal bond, not yet drawn drawn[id(bond)] = bond bond.draw(glpane, disp, bondcolor, drawLevel, special_drawing_handler = self.special_drawing_handler ) except: # [bruce 041028 general workaround to make bugs less severe] # exception in drawing one atom. Ignore it and try to draw the # other atoms. #e In future, draw a bug-symbol in its place. print_compact_traceback("exception in drawing one atom or bond ignored: ") try: print "current atom was:", atom except: print "current atom was... exception when printing it, discarded" try: atom_source = atom._f_source # optional atom-specific debug info except AttributeError: pass else: print "Source of current atom:", atom_source return # from _standard_draw_atoms (submethod of _draw_for_main_display_list) def overdraw_hotspot(self, glpane, disp): #bruce 050131 #### REVIEW: ok if this remains outside any CSDL? # A possible issue is whether it's big enough (as a polyhedral sphere) # to completely cover an underlying shader sphere. """ If self._chunk is a (toplevel) clipboard item with a hotspot (i.e. if pasting it onto a bondpoint will work and use its hotspot), draw its hotspot in a special manner. @note: As with selatom, we do this outside of the display list. """ if self._should_draw_hotspot(glpane): hs = self._chunk.hotspot try: color = env.prefs[bondpointHotspotColor_prefs_key] #bruce 050808 level = self._chunk.assy.drawLevel #e or always use best level?? ## code copied from selatom.draw_as_selatom(glpane, disp, color, level) pos1 = hs.baseposn() drawrad1 = hs.highlighting_radius(disp) ## drawsphere(color, pos1, drawrad1, level) # always draw, regardless of disp hs.draw_atom_sphere(color, pos1, drawrad1, level, None, abs_coords = False) #bruce 070409 bugfix (draw_atom_sphere); important if it's really a cone except: msg = "debug: ignoring exception in overdraw_hotspot %r, %r" % \ (self, hs) print_compact_traceback(msg + ": ") pass pass return def _should_draw_hotspot(self, glpane): #bruce 080723 split this out, cleaned it up """ Determine whether self has a valid hotspot and wants to draw it specially. """ # bruce 050416 warning: the conditions here need to match those in depositMode's # methods for mentioning hotspot in statusbar, and for deciding whether a clipboard # item is pastable. All this duplicated hardcoded conditioning is bad; needs cleanup. #e # We need these checks because some code removes singlets from a chunk (by move or kill) # without checking whether they are that chunk's hotspot. # review/cleanup: some of these checks might be redundant with checks # in the get method run by accessing self._chunk.hotspot. hs = self._chunk.hotspot ### todo: move lower, after initial tests wanted = (self in self._chunk.assy.shelf.members) or glpane.always_draw_hotspot #bruce 060627 added always_draw_hotspot re bug 2028 if not wanted: return False if hs is None: return False if not hs.is_singlet(): return False if not hs.key in self._chunk.atoms: return False return True pass # end of class ChunkDrawer # end
NanoCAD-master
cad/src/graphics/model_drawing/ChunkDrawer.py
# Copyright 2004-2009 Nanorex, Inc. See LICENSE file for details. """ TransformedDisplayListsDrawer.py - abstract class for something that draws using display lists which it caches under a local coordinate system. Note: as of 090213-17 this contains common code which is used, though the "transformed" aspects are still not implemented or not used, and there is still a lot of potential common code in the subclasses (mainly in the draw method) not yet in this superclass since highly nontrivial to refactor. @author: Bruce @version: $Id$ @copyright: 2004-2009 Nanorex, Inc. See LICENSE file for details. This code relates to: - frustum culling(?) - caching of multiple display lists (e.g. one per display style) - display lists drawn under a transform; modifying them as needed if transform changes (needed by vertex arrays in CSDLs, not by pure OpenGL display lists) - usage/change tracking related to display list contents TODO: unify similar code in three places: here, ChunkDrawer, ExtraChunkDisplayList. ### """ from utilities.debug_prefs import debug_pref, Choice_boolean_True from foundation.changes import SelfUsageTrackingMixin, SubUsageTrackingMixin #bruce 050804, so glpanes can know when they need to redraw a chunk's display list, # and chunks can know when they need to inval that because something drawn into it # would draw differently due to a change in some graphics pref it used from graphics.drawing.ColorSortedDisplayList import ColorSortedDisplayList # not yet used? # == class TransformedDisplayListsDrawer(object, SelfUsageTrackingMixin, SubUsageTrackingMixin ): """ Superclass for drawing classes which make use of one or more display lists (actually CSDLs) to be drawn relative to a transform known to the specific subclass, and to be invalidated at appropriate times (with help from the subclass). (The specific subclass knows where to get the transform, and when to invalidate the display lists beyond when usage tracking does so.) """ # todo (someday): might be partly obs as of 090217; # OTOH some of it doesn't apply yet until ExternalBondSetDrawer # handles transforms (to optimize drag): # # to pull in more of the subclass draw methods, # we'd need the following attrs, or revised code: # - assy # for drawLevel # - glname # if there is a "whole-chunk" one for all our primitives # - get_dispdef # method in subclass -- not in the API?? maybe it is if # it's "get cache key and style args" ### # - is_chunk_visible # ??? # - applyMatrix # but not get_display_mode_handler, delegate_*, hd, chunk_only -- # that is handled outside by choosing the right rule (this class) _havelist_inval_counter = 0 # see also self.havelist # there is no class default for displist; see __get_displist. glpane = None havelist = 0 def __init__(self): # note: self.displist is allocated on demand by __get_displist # [bruce 070523] self.extra_displists = {} # precaution, probably not needed ### REFACTOR: the code to make these is not in this class # or even in the subclass ChunkDrawer, but in a cooperating object # Chunk_SpecialDrawingHandler -- probably that ought to be calling # back to ChunkDrawer to make this, so only this class and its # subclasses would know about self.extra_displists, and so # this class could have methods to fill it in which its # subclass would be overriding. [bruce 090224 comment] return # == def invalidate_display_lists_for_style(self, style): #bruce 090217 """ @see: documentation of same method in class Chunk [this is a conservative implementation; many subclasses will want to override this as an optimization] """ self.invalidate_display_lists() return # ====== #### note: many following methods were moved here from our subclass Chunk # by bruce 090213, but their docstrings and comments are mostly not yet # updated for that move. def invalidate_display_lists(self): #bruce 050804, revised 090212 """ [public, though uses outside this class or class Chunk are suspicious re modularity, and traditionally have been coded as changeapp calls on Chunk instead] This is meant to be called when something whose usage we tracked (while making our main display list) next changes. """ # note: the old code when this was in class Chunk and used mainly # for end_tracking_usage invalidator was: ## self.changeapp(0) # that now tells self.glpane to update, if necessary # but I think the correct code should have been more like this, all along: self.havelist = 0 self.track_inval() #### REVIEW: all comments about track_inval, havelist, changeapp, # and whether the old code did indeed do changeapp and thus gl_update_something. # note: as of 090216, in our subclass ExternalBondSetDrawer, this is # called at least once per external bond (rung bond) when dna is being # rigidly dragged. Once TransformNode works well enough, it won't be # called at all for rigid drag. (It will still be called often in some # other cases, so it ought to be fast.) return # == Methods relating to our main OpenGL display list (or CSDL), # self.displist [revised, bruce 090212] # (Note: most of these methods could be moved to a new superclass # concerned with maintaining self.displist for any sort of object # that needs one (TransformedDisplayListsDrawer?). If that's done, see also # GLPane_mixin_for_DisplayListChunk for useful features of other # kinds to integrate into that code. But note that a typical object # probably needs a dictionary of displists for different uses, # not just a single one -- even this class has some like that, # in self.extra_displists. That might be more useful to generalize. # [bruce 071103/090123/090212 comment]) # Note: to invalidate the drawing effects of # executing self.displist (along with our extra_displists), # when our graphical appearance changes, # we set self.havelist = 0 and sometimes call track_inval. # The external interface to that is invalidate_display_lists. # # As for the display list name or CSDL itself, it's allocated on demand # (during drawing, when the right GL context is sure to be current), # and discarded when we're killed, using the self.displist property # that follows. _displist = None def __get_displist(self): """ get method for self.displist property: Initialize self._displist if necessary, and return it. @note: This must only be called when the correct GL context is current. (If several contexts share display lists, it doesn't matter which one is current, but one of them must be.) There is no known way to check this, but ignoring it will cause bugs. The simplest way to be sure of this is to call this method only during drawing. """ if not self._displist: self._displist = ColorSortedDisplayList(self.getTransformControl()) return self._displist def getTransformControl(self): #bruce 090223 """ @return: the transformControl to use for our ColorSortedDisplayLists (perhaps None) [subclasses should override as needed] """ return None def __set_displist(self): """ set method for self.displist property; should never be called """ assert 0 def __del_displist(self): """ del method for self.displist property @warning: doesn't deallocate OpenGL display lists; caller must do that first if desired """ self._displist = None ### review: pull more of the deallocator into here? displist = property(__get_displist, __set_displist, __del_displist) def _has_displist(self): """ @return: whether we presently have a valid display list name (or equivalent object), as self.displist. @rtype: boolean @note: not the same as self.havelist, which contains data related to whether self.displist not only exists, but has up to date contents. """ return self._displist is not None # new feature [bruce 071103]: # deallocate display lists of killed chunks. # TODO items re this: # - doc the fact that self.displist can be different when chunk kill is undone # - worry about ways chunks can miss out on this: # - created, then undo that # - no redraw, e.g. for a thumbview in a dialog that gets deleted... # maybe ok if user ever shows it again, but what if they never do? # - probably ok, but need to test: # - close file, or open new file # - when changing to a new partlib part, old ones getting deleted # - create chunk, undo, redo, etc or then kill it # - kill chunk, undo, redo, undo, etc or then kill it def _immediately_deallocate_displists(self): #bruce 071103 """ [private method] Deallocate our OpenGL display lists, and make sure they'll be reallocated when next needed. @warning: This always deallocates and always does so immediately; caller must ensure this is desired and safe at this time (e.g. that our GL context is current). """ if self._has_displist(): #russ 080225: Moved deallocation into ColorSortedDisplayList class # for ColorSorter. self.displist.deallocate_displists() for extra_displist in self.extra_displists.values(): extra_displist.deallocate_displists() self.extra_displists = {} del self.displist # note: runs __del_displist due to a property # this del is necessary, so __get_displist will allocate another # display list when next called (e.g. if a killed chunk is revived by Undo) self.havelist = 0 self._havelist_inval_counter += 1 # precaution, need not analyzed ## REVIEWED: this self.glpane = None seems suspicious, # but removing it could mess up _gl_context_if_any # if that needs to return None, but the docstring of that # says that our glpane (once it occurs) is permanent, # so I think it should be more correct to leave it assigned here # than to remove it (e.g. conceivably removing it could prevent # deallocation of DLs when that should happen, though since it's # happening now, that seems unlikely, but what if this code is # extended to deallocate other DLs on self, one at a time). # OTTH what if this is needed to remove a reference cycle? # but that can't matter for a permanent glpane # and can be fixed for any by removing its ref to the model. # Conclusion: best not to remove it here, though pre-090212 # code did remove it. [bruce 090212] ## self.glpane = None pass def _deallocate_displist_later(self): #bruce 071103 """ At the next convenient time when our OpenGL context is current, if self._ok_to_deallocate_displist(), call self._immediately_deallocate_displists(). """ self.call_when_glcontext_is_next_current( self._deallocate_displist_if_ok ) return def _deallocate_displist_if_ok(self): #bruce 071103 if self._ok_to_deallocate_displist(): self._immediately_deallocate_displists() return def _ok_to_deallocate_displist(self): #bruce 071103 """ Say whether it's ok to deallocate self's OpenGL display list right now (assuming our OpenGL context is current). [subclasses must override this] """ raise Exception("subclass must implement") def _gl_context_if_any(self): #bruce 071103 """ If self has yet been drawn into an OpenGL context, return a GLPane_minimal object which corresponds to it; otherwise return None. (Note that self can be drawn into at most one OpenGL context during its lifetime, except for contexts which share display list names.) """ # (I'm not sure whether use of self.glpane is a kluge. # I guess it would not be if we formalized what it already means.) return self.glpane def call_when_glcontext_is_next_current(self, func): #bruce 071103 """ """ glpane = self._gl_context_if_any() if glpane: glpane.call_when_glcontext_is_next_current(func) return def deallocate_displist_if_needed(self): """ If we can and need to deallocate our display lists, do so when next safe and convenient (if it's still ok then). """ # bruce 090123 split this out if self._enable_deallocate_displist(): need_to_deallocate = self._ok_to_deallocate_displist() if need_to_deallocate: ## print "undo or redo calling _deallocate_displist_later on %r" % self self._deallocate_displist_later() return def _f_kill_displists(self): #bruce 090123 split this out of Chunk.kill """ Private helper for model kill methods such as Chunk.kill """ if self._enable_deallocate_displist(): self._deallocate_displist_later() #bruce 071103 return def _enable_deallocate_displist(self): res = debug_pref("GLPane: deallocate OpenGL display lists of killed objects?", Choice_boolean_True, # False is only useful for debugging prefs_key = True ) return res def _f_kluge_set_selectedness_for_drawing(self, picked): """ private helper for performing necessary side effects (on our behavior when we subsequently draw) of Chunk.pick and Chunk.unpick. @note: won't be needed once CSDL stops storing picked state; also could probably be removed as an external API call by calling it with self._chunk.picked at the start of our own drawing methods. """ #bruce 090123 split this out of Chunk.pick and Chunk.unpick; # REFACTOR: should not be needed once CSDL stops storing picked state if self._has_displist(): #bruce 090223 added condition self.displist.selectPick(picked) # Note: selectPick shouldn't be needed for self.extra_displists, # due to how they're drawn. ### REVIEW [bruce 090114]: is selectPick still needed for # self.displist? If not, is the CSDL picked state still needed # for anything? (A goal is to remove it entirely.) For status on # this, see my 090114 comments in ColorSorter.py (summary: it is # almost but not quite possible to remove it now). return # ===== # support for collect_drawing_func [bruce 090312] # note: this is only for local drawing (in self's local coords); # if we also need absolute model coord drawing # we should add another persistent CSDL for that, # and another collector (or an option to this one) # to add funcs to it. _csdl_for_funcs = None # once allocated, never changed and always drawn def begin_collecting_drawing_funcs(self): if self._csdl_for_funcs: self._csdl_for_funcs.clear_drawing_funcs() def collect_drawing_func(self, func, *args, **kws): if not self._csdl_for_funcs: tc = self.getTransformControl() csdl = self._csdl_for_funcs = ColorSortedDisplayList( tc) # review: I think we needn't explicitly deallocate this csdl # since it contains no DLs. Am I right? [bruce 090312 Q] else: csdl = self._csdl_for_funcs if args or kws: func = (lambda _args = args, _kws = kws, _func = func: _func(*_args, **_kws) ) csdl.add_drawing_func( func ) return def end_collecting_drawing_funcs(self, glpane): if self._csdl_for_funcs: glpane.draw_csdl( self._csdl_for_funcs ) return # ===== def draw(self, glpane): raise Exception("subclass must implement") # someday, we'll either have a real draw method here, # or at least some significant helper methods for it. pass # end of class # end
NanoCAD-master
cad/src/graphics/model_drawing/TransformedDisplayListsDrawer.py
NanoCAD-master
cad/src/graphics/behaviors/__init__.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ Trackball.py - one kind of Trackball. class Trackball produces incremental quaternions using a mapping of the screen onto a sphere, tracking the cursor on the sphere. @author: Josh @version: $Id$ @copyright: 2004-2007 Nanorex, Inc. See LICENSE file for details. Note: bruce 071216 moved class Trackball into its own file, from VQT.py. """ import foundation.env as env from utilities.prefs_constants import mouseSpeedDuringRotation_prefs_key from geometry.VQT import Q from geometry.VQT import proj2sphere class Trackball: """ A trackball object. """ #bruce 060514 revisions: # - add/revise some docstrings and comments # - compare vectors and quats to None rather than using boolean tests (possible bugfix) # - clean up some duplicated code # Planned generalizations (nim): let a global setting control the trackball algorithm. # (In principle, that should be supplied by the caller, since it's associated with # the interface in which the trackball is being used.) def __init__(self, wide, high): """ Create a Trackball object. Arguments are window width and height in pixels (the same as for self.rescale()), or can be guesses if the caller will call self.rescale() with correct arguments before the trackball is used. """ self.rescale(wide, high) self.quat = Q(1,0,0,0) self.oldmouse = None # note: oldmouse and newmouse are not mouse positions; they come out of proj2sphere. # I think they're related to a non-incremental trackball goal; not sure yet. [bruce 060514 comment] self.mouseSpeedDuringRotation = None def rescale(self, wide, high): """ This should be called when the trackball's window or pane has been resized to the given values (window width and height in pixels). """ self.w2 = wide / 2.0 self.h2 = high / 2.0 self.scale = 1.1 / min( wide / 2.0, high / 2.0) def start(self, px, py): """ This should be called in a mouseDown binding, with window coordinates of the mouse. """ # ninad060906 initializing the factor 'mouse speed during rotation' # here instead of init so that it will come into effect immediately self.mouseSpeedDuringRotation = \ env.prefs[ mouseSpeedDuringRotation_prefs_key] self.oldmouse = proj2sphere( (px - self.w2) * self.scale * self.mouseSpeedDuringRotation, (self.h2 - py) * self.scale * self.mouseSpeedDuringRotation ) def update(self, px, py, uq = None): """ This should be called in a mouseDrag binding, with window coordinates of the mouse; return value is an incremental quat, to be used in conjunction with uq as explained below. For trackballing the entire model space (whose orientation is stored in (for example) glpane.quat), caller should not pass uq, and should increment glpane.quat by the return value (i.e. glpane.quat += retval). For trackballing an object with orientation obj.quat, drawn subject to (for example) glpane.quat, caller should pass uq = glpane.quat, and should increment obj.quat by the return value. (If caller didn't pass uq in that case, our retval would be suitable for incrementing obj.quat + glpane.quat, or glpane.quat alone, but this is not the same as a retval suitable for incrementing obj.quat alone.) """ #bruce 060514 revised this code (should be equivalent to the prior code), added docstring #ninad 060906 added 'rotation sensitivity to this formula. the rotation sensitivity will be used #while middle drag rotating the model. By default a lower value is set for this and can be adjusted #via a user preference. This helps mitigate bug 1856 newmouse = proj2sphere((px - self.w2) * self.scale * self.mouseSpeedDuringRotation, (self.h2 - py) * self.scale * self.mouseSpeedDuringRotation) if self.oldmouse is not None: quat = Q(self.oldmouse, newmouse) if uq is not None: quat = uq + quat - uq else: print "warning: trackball.update sees oldmouse is None (should not happen)" #bruce 060514 quat = Q(1,0,0,0) self.oldmouse = newmouse return quat pass # end of class Trackball # end
NanoCAD-master
cad/src/graphics/behaviors/Trackball.py
# Copyright 2007-2008 Nanorex, Inc. See LICENSE file for details. """ confirmation_corner.py -- helpers for modes with a confirmation corner (or other overlay widgets). @author: Bruce @version: $Id$ @copyright: 2007-2008 Nanorex, Inc. See LICENSE file for details. Note: confirmation corners make use of two methods added to the "GraphicsMode API" (the one used by GLPane to interface to glpane.graphicsMode for mouse and drawing) for their sake, currently [071015] defined only in basicGraphicsMode: draw_overlay, and mouse_event_handler_for_event_position. These are general enough to handle all kinds of overlays, in principle, but the current implem and some API details may be just barely general enough for the confirmation corner. Those method implems assume that Command subclasses (at least those which can be found by GraphicsMode.draw_overlay -- namely, those which supply their own PM, as of 080905) override want_confirmation_corner_type to return the kind of confirmation corner they want at a given moment. """ import os from exprs.ExprsConstants import PIXELS from exprs.images import Image from exprs.Overlay import Overlay from exprs.instance_helpers import get_glpane_InstanceHolder from exprs.Rect import Rect # needed for Image size option, not just for testing ##from constants import green # only for testing from exprs.projection import DrawInCorner ##, DrawInCorner_projection from utilities.prefs_constants import UPPER_RIGHT from utilities.debug import print_compact_traceback ##, print_compact_stack from utilities.debug_prefs import debug_pref, Choice_boolean_False # button region codes (must all be true values; # these are used as indices in various dicts or functions, # and are used as components of cctypes like 'Done+Cancel') BUTTON_CODES = ('Done', 'Cancel', 'Transient-Done') # == class MouseEventHandler_API: #e refile #e some methods may need graphicsMode and/or glpane arg... """ API (and default method implems) for the MouseEventHandler interface (for objects used as glpane.mouse_event_handler) [abstract class] """ def mouseMoveEvent(self, event): """ """ pass def mouseDoubleClickEvent(self, event): """ """ pass def mousePressEvent(self, event): """ """ pass def mouseReleaseEvent(self, event): """ """ pass def update_cursor(self, graphicsMode, wpos): """ Perform side effects in graphicsMode (assumed to be a basicGraphicsMode subclass) to give it the right cursor for being over self at position <wpos> (in OpenGL window coords). """ ###e may need more args (like mod keys, etc), # or official access to more info (like glpane.button), # to choose the cursor pass def want_event_position(self, wX, wY): """ Return a true value if self wants to handle mouse events at the given OpenGL window coords, false otherwise. Note: some implems, in the true case, actually return some data indicating what cursor and display state they want to use; it's not yet decided whether this is supported in the official API (it's not yet) or merely permitted for internal use (it is and always will be). """ pass def draw(self): """ """ pass pass # == # exprs for images # overlay image (command-specific icon) # This draws a 22 x 22 icon in the upper left corner of the glpane. # I need to be able to change the origin of the icon so it can be drawn at # a different location inside the confirmation corner, but I cannot # figure out how to do this. I will discuss with Bruce soon. -Mark 2008-03-23 _overlay_image = Image(convert = 'RGBA', decal = False, blend = True, #ideal_width = 22, #ideal_height = 22, size = Rect(22 * PIXELS)) from exprs.transforms import Translate from exprs.Exprs import V_expr from exprs.Rect import Spacer def _expr_for_overlay_imagename(imagename, dx = 0, dy = 0): # WARNING: this is not optimized (see comment for _expr_for_imagename()). image_expr = _overlay_image( imagename ) # NOTE: If the desired dx,dy depends on other settings, # like whether one or two CC buttons are shown, # then it's simplest to make more variants of this expr, # with dx, dy hardcoded differently in each one. # Or if that's not practical, let me know and I'll # revise the code that draws this to accomodate that variability. # Also make sure to revise the code that calls each one # (i.e. a modified copy of _expr_instance_for_overlay_imagename) # to use a different "index" even when using the same imagename. # (For example, it could include dx,dy in the index.) # [bruce 080324] return DrawInCorner(corner = UPPER_RIGHT)( Overlay( Spacer(22 * PIXELS), Translate( image_expr, V_expr(dx * PIXELS, dy * PIXELS, 0)), ) ) # == # button images _trans_image = Image(convert = 'RGBA', decal = False, blend = True, # don't need (I think): alpha_test = False shape = 'upper-right-half', #bruce 070628 maybe this will fix bug 2474 (which I can't see on Mac); # note that it has a visible effect on Mac (makes the intended darker edge of the buttons less thick), # but this seems ok. clamp = True, # this removes the artifacts that show the edges of the whole square of the image file ideal_width = 100, ideal_height = 100, size = Rect(100 * PIXELS)) def _expr_for_imagename(imagename): # WARNING: this is not optimized -- it recomputes and discards this expr on every access! # (But it looks like its caller, _expr_instance_for_imagename, caches the expr instances, # so only the uninstantiated expr itself is recomputed each time, so it's probably ok. # [bruce 080323 comment]) if '/' not in imagename: imagename = os.path.join( "ui/confcorner", imagename) image_expr = _trans_image( imagename ) return DrawInCorner(corner = UPPER_RIGHT)( image_expr ) # == # These IMAGENAMES are used only for a preloading optimization. # If this list is not complete, it will not cause bugs, # it will just mean the first use of certain images is slower # (but startup is faster by the same amount). # [bruce 080324 comment] IMAGENAMES = """ CancelBig.png CancelBig_Pressed.png DoneBig.png DoneBig_Pressed.png DoneSmall_Cancel_Pressed.png DoneSmall.png DoneSmall_Pressed.png TransientDoneSmall.png TransientDoneSmall_Pressed.png TransientDoneSmall_Cancel_Pressed.png TransientDoneBig.png TransientDoneBig_Pressed.png""".split() # == class cc_MouseEventHandler(MouseEventHandler_API): #e rename # an instance can be returned from find_or_make_confcorner_instance """ ###doc """ # initial values of state variables, etc _last_button_position = False # False or an element of BUTTON_CODES _pressed_button = False # False or an element of BUTTON_CODES; valid regardless of self.glpane.in_drag _cctype = -1 # intentionally illegal value, different from any real value # review: are self.glpane and self.command, set below, private? # if so, should rename them to indicate this. [bruce 080323 comment] def __init__(self, glpane): self.glpane = glpane for imagename in IMAGENAMES: self._preload(imagename) # to avoid slowness when each image is first used in real life return def _preload(self, imagename): self._expr_instance_for_imagename(imagename) return def _expr_instance_for_imagename(self, imagename): ih = get_glpane_InstanceHolder(self.glpane) index = imagename # might have to be more unique if we start sharing this InstanceHolder with anything else expr = _expr_for_imagename(imagename) expr_instance = ih.Instance( expr, index, skip_expr_compare = True) return expr_instance def _expr_instance_for_overlay_imagename(self, imagename, dx = 0, dy = 0): ih = get_glpane_InstanceHolder(self.glpane) index = 1, imagename # might have to be more unique if we start sharing this InstanceHolder with anything else expr = _expr_for_overlay_imagename(imagename, dx, dy) expr_instance = ih.Instance( expr, index, skip_expr_compare = True) return expr_instance def _f_advise_find_args(self, cctype, command): """ [friend method; can be called as often as every time this is drawn; cctype can be None or one of a few string constants.] Set self._button_codes correctly for cctype and command, also saving those in attrs of self of related names. self.command is used later for: - finding PM buttons for doing actions - finding the icon for the Done button, from the PM """ self.command = command if self._cctype != cctype: # note: no point in updating drawing here if cctype changes, # since we're only called within glpane calling graphicsMode.draw_overlay. ## self._update_drawing() self._cctype = cctype if cctype: self._button_codes = cctype.split('+') assert len(self._button_codes) in (1, 2) for bc in self._button_codes: assert bc in BUTTON_CODES else: self._button_codes = [] return # == event position (internal and _API methods), and other methods ###DESCRIBE better def want_event_position(self, wX, wY): """ MouseEventHandler_API method: Return False if we don't want to be the handler for this event and immediately after it; return a true button-region-code if we do. @note: Only called externally when mouse is pressed (glpane.in_drag will already be set then), or moves when not pressed (glpane.in_drag will be unset); deprecated for internal calls. The current implem does not depend on only being called at those times, AFAIK. """ return self._button_region_for_event_position(wX, wY) def _button_region_for_event_position(self, wX, wY): """ Return False if wX, wY is not over self, or a button-region-code (whose boolean value is true; an element of BUTTON_CODES) if it is, which says which button region of self it's over (regardless of pressed state of self). """ # correct implem, but button-region size & shape is hardcoded dx = self.glpane.width - wX dy = self.glpane.height - wY if dx + dy <= 100: # this event is over the CC triangular region; which of our buttons is it over? if len(self._button_codes) == 2: if -dy >= -dx: # note: not the same as wY >= wX if glpane is not square! return self._button_codes[0] # top half of corner triangle; usually 'Done' else: return self._button_codes[1] # right half of corner triangle; usually 'Cancel' elif len(self._button_codes) == 1: return self._button_codes[0] else: return False # can this ever happen? I don't know, but if it does, it should work. return False def _transient_overlay_icon_name(self, imagename): """ Returns the transient overlay icon filename to include in the confirmation corner. This is the current command's icon that is used in the title of the property manager. @param imagename: Confirmation corner imagename. @type imagename: string @return: Iconpath of the image to use as an overlay in the confimation corner, delta x and delta y translation for positioning the icon in the confirmation corner. @rtype: string, int, int """ if "Transient" in imagename: if "Big" in imagename: dx = -46 dy = -6 else: dx = -51 dy = -1 return (self.command.propMgr.iconPath, dx, dy) return (None, 0, 0) def draw(self): """ MouseEventHandler_API method: draw self. Assume background is already correct (so our implem can be the same, whether the incremental drawing optim for the rest of the GLPane content is operative or not). """ if 0: print "draw CC for cctype %r and state %r, %r" \ % (self._cctype, self._pressed_button, self._last_button_position) # figure out what image expr to draw # NOTE: this is currently not nearly as general as the rest of our # logic, regarding what values of self._button_codes are supported. # If we need it to be more general, we can split the expr into two # triangular pieces, using Image's shape option and Overlay, so its # two buttons are independent (as is done in some of the tests in # exprs/test.py). if self._button_codes == []: # the easy case return elif self._button_codes == ['Cancel']: if self._pressed_button == 'Cancel': imagename = "CancelBig_Pressed.png" else: imagename = "CancelBig.png" elif self._button_codes == ['Done']: if self._pressed_button == 'Done': imagename = "DoneBig_Pressed.png" else: imagename = "DoneBig.png" elif self._button_codes == ['Done', 'Cancel']: if self._pressed_button == 'Done': imagename = "DoneSmall_Pressed.png" elif self._pressed_button == 'Cancel': imagename = "DoneSmall_Cancel_Pressed.png" else: imagename = "DoneSmall.png" elif self._button_codes == ['Transient-Done', 'Cancel']: if self._pressed_button == 'Transient-Done': imagename = "TransientDoneSmall_Pressed.png" elif self._pressed_button == 'Cancel': imagename = "TransientDoneSmall_Cancel_Pressed.png" else: imagename = "TransientDoneSmall.png" elif self._button_codes == ['Transient-Done']: if self._pressed_button == 'Transient-Done': imagename = "TransientDoneBig_Pressed.png" else: imagename = "TransientDoneBig.png" else: assert 0, "unsupported list of buttoncodes: %r" \ % (self._button_codes,) expr_instance = self._expr_instance_for_imagename(imagename) ### REVIEW: worry about value of PIXELS vs perspective? ### worry about depth writes? expr_instance.draw() # Note: this draws expr_instance in the same coordsys used for # drawing the model. overlay_imagename, dx, dy = self._transient_overlay_icon_name(imagename) if overlay_imagename: expr_instance = \ self._expr_instance_for_overlay_imagename(overlay_imagename, dx, dy) expr_instance.draw() return def update_cursor(self, graphicsMode, wpos): """ MouseEventHandler_API method; change cursor based on current state and event position """ assert self.glpane is graphicsMode.glpane win = graphicsMode.win # for access to cursors wX, wY = wpos bc = self._button_region_for_event_position(wX, wY) # figure out want_cursor (False or a button code; in future there may # be other codes for modified cursors) if not self._pressed_button: # mouse is not down; cursor reflects where we are at the moment # (False or a button code) want_cursor = bc else: # a button is pressed; cursor reflects whether this button will act # or not (based on whether we're over it now or not) # (for now, if the button will act, the cursor does not look any # different than if we're hovering over the button, but revising # that would be easy) if self._pressed_button == bc: want_cursor = bc else: want_cursor = False # show the cursor indicated by want_cursor if want_cursor: assert want_cursor in BUTTON_CODES if want_cursor == 'Done': cursor = win._confcorner_OKCursor elif want_cursor == 'Transient-Done': cursor = win.confcorner_TransientDoneCursor else: cursor = win._confcorner_CancelCursor self.glpane.setCursor(cursor) else: # We want to set a cursor which indicates that we'll do nothing. # Modes won't tell us that cursor, but they'll set it as a side # effect of graphicsMode.update_cursor_for_no_MB(). # Actually, they may set the wrong cursor then (e.g. BuildCrystal_Command, # which looks at glpane.modkeys, but if we're here with modkeys # we're going to ignore them). If that proves to be misleading, # we'll revise this. self.glpane.setCursor(win.ArrowCursor) # in case the following method does nothing (can happen) try: graphicsMode.update_cursor_for_no_MB() # _no_MB is correct, even though a button is presumably # pressed. except: print_compact_traceback("bug: exception (ignored) in %r.update_cursor_for_no_MB(): " % (graphicsMode,) ) pass return # == mouse event handling (part of the _API) def mousePressEvent(self, event): # print "meh press" wX, wY = wpos = self.glpane._last_event_wXwY bc = self._button_region_for_event_position(wX, wY) self._last_button_position = bc # this is for knowing when our appearance might change self._pressed_button = bc # this and glpane.in_drag serve as our state variables if not bc: print "bug: not bc in meh.mousePressEvent" # should never happen; if it does, do nothing else: self._update_drawing() return def mouseMoveEvent(self, event): ###e should we get but & mod as new args, or from glpane attrs set by fix_event?? wX, wY = wpos = self.glpane._last_event_wXwY # or we could get these from event bc = self._button_region_for_event_position(wX, wY) if self._last_button_position != bc: self._last_button_position = bc self._update_drawing() self._do_update_cursor() return def mouseReleaseEvent(self, event): # print "meh rel" wX, wY = self.glpane._last_event_wXwY bc = self._button_region_for_event_position(wX, wY) if self._last_button_position != bc: print "unexpected: self._last_button_position != bc in meh.mouseReleaseEvent (should be harmless)" ### self._last_button_position = bc if self._pressed_button and self._pressed_button == bc: #e in future: if action might take time, maybe change drawing appearance to indicate we're "doing it" self._do_action(bc) self._pressed_button = False self._update_drawing() # might be redundant with _do_action (which may need to update even more, I don't know for sure) # Note: this might not be needed if no action happens -- depends on nature of highlighting; # note that you can press one button and release over the other, and then the other might need to highlight # if it has mouseover highlighting (tho in current design, it doesn't). self._do_update_cursor() # probably not needed (but should be ok as a precaution) return # == internal update methods def _do_update_cursor(self): ### TODO: REVISE DOCSTRING; it's unclear after recent changes [bruce 070628] """ internal helper for calling our external API method update_cursor with the right arguments -- but only if we're still responsible for the cursor according to the GLPane -- otherwise, call the one that is! """ self.glpane.graphicsMode.update_cursor() #bruce 070628 revised this as part of fixing bug 2476 (leftover CC Done cursor). # Before, it called our own update_cursor, effectively assuming we're still active, # wrong after a release and button action. Now, this is redundant in that case, but # should be harmless; it might still be needed in the move case (though probably self # is always active then). return def _update_drawing(self): ### TODO: figure out if our appearance has changed, and do nothing if not (important optim) # (be careful about whether we're the last CC to be drawn, if there's more than one and they get switched around! # we might need those events about enter/leave that the glpane doesn't yet send us; or some about changing the cc) ### self.glpane.gl_update_confcorner() # note: as of 070627 this is the same as gl_update -- NEEDS OPTIM to be incremental # == internal action methods def _do_action(self, buttoncode): """ do the action corresponding to buttoncode (protected from exceptions) """ #e in future: statusbar message? # print "_do_action", buttoncode ###REVIEW: maybe all the following should be a Command method? # Note: it will all get revised and cleaned up once we have a command stack # and we can just tell the top command to do Done or Cancel. done_button, cancel_button = self.command._KLUGE_visible_PM_buttons() # each one is either None, or a QToolButton (a true value) currently displayed on the current PM if buttoncode in ['Done', 'Transient-Done']: button = done_button else: button = cancel_button if not button: print "bug (ignored): %r trying to do action for nonexistent %r button" % (self, buttoncode) #e more info? else: try: # print "\nabout to click %r button == %r" % (buttoncode, button) button.click() # This should make the button emit the clicked signal -- not sure if it will also emit # the pressed and released signals. The Qt doc (for QAbstractButton.click) just says # "All the usual signals associated with a click are emitted as appropriate." # Our code mostly connects to clicked, but for a few buttons (not the ones we have here, I think) # connects to pressed or released. Search for those words used in a SIGNAL macro to find them. # Assume the click handler did whatever updates were required, # as it would need to do if the user pressed the button directly, # so no updates are needed here. That's good, because only the event handler # knows if some are not needed (as an optimization). # print "did the click" except: print_compact_traceback("bug: exception (ignored) when using %r button == %r: " % (buttoncode, button,) ) pass # we did the action; now (at least for Done or Cancel), we should inactivate self as mouse_event_handler # and then do update_cursor, which the following does (part of fixing bug 2476 (leftover CC Done cursor)) # [bruce 070628] self.glpane.set_mouse_event_handler(None) pass return pass # end of class cc_MouseEventHandler # == def find_or_make_confcorner_instance(cctype, command): """ Return a confirmation corner instance for command, of the given cctype. [Public; called from basicGraphicsMode.draw_overlay] """ try: command._confirmation_corner__cached_meh except AttributeError: command._confirmation_corner__cached_meh = cc_MouseEventHandler(command.glpane) res = command._confirmation_corner__cached_meh res._f_advise_find_args(cctype, command) # in case it wants to store these # (especially since it's shared for different values of them) return res # see also exprs/cc_scratch.py # end
NanoCAD-master
cad/src/graphics/behaviors/confirmation_corner.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ shape.py -- handle freehand curves for selection and crystal-cutting @author: Josh, Huaicai, maybe others @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: By Josh. Portions rewritten or extended by at least Bruce & Huaicai, perhaps others. Bruce 071215 split classes CrystalShape and Slab into their own modules. Module classification and refactoring: [bruce 071215] Perhaps SelectionShape should also be split out? The rest seems pretty closely integrated, though it may still be "vertically integrated" in the sense of combining several kinds of code, including geometry, graphics_behavior (incl selection), maybe more. The public defs are at least get_selCurve_color, simple_shape_2d, shape, SelectionShape. For now, I'll guess that I can call all these "graphics_behavior". We'll see. (This feels more natural than "operations", though for that I'd be more confident that a package import cycle was unlikely.) """ from Numeric import array, zeros, maximum, minimum, ceil, dot, floor from geometry.VQT import A, vlen, V from graphics.drawing.drawers import drawrectangle from graphics.drawing.CS_draw_primitives import drawline from utilities.constants import black from utilities.constants import DELETE_SELECTION from utilities.constants import SUBTRACT_FROM_SELECTION from utilities.constants import ADD_TO_SELECTION from utilities.constants import START_NEW_SELECTION from utilities.constants import white from utilities.constants import red from utilities.debug import print_compact_traceback from utilities import debug_flags import foundation.env as env ##from utilities.constants import colors_differ_sufficiently from utilities.prefs_constants import DarkBackgroundContrastColor_prefs_key from utilities.prefs_constants import LightBackgroundContrastColor_prefs_key from geometry.BoundingBox import BBox def get_selCurve_color(selSense, bgcolor = white): """ [public] Returns line color of the selection curve. Returns <black> for light colored backgrounds (and Sky Blue). Returns <white> for dark colored backgrounds. Returns <red> if <selSense> is DELETE_SELECTION mode. """ if selSense == DELETE_SELECTION: return red # Problems with this when the user picks a light gradient (i.e. Blue Sky) # but the bgcolor is a dark color. Simply returning # "DarkBackgroundContrastColor_prefs_key" works fine. Mark 2008-07-10 #if colors_differ_sufficiently(bgcolor, black): # return env.prefs[DarkBackgroundContrastColor_prefs_key] #else: # return env.prefs[LightBackgroundContrastColor_prefs_key] return env.prefs[DarkBackgroundContrastColor_prefs_key] def fill(mat, p, dir): # TODO: rename (less generic so searchable), and perhaps make private """ [helper for class curve; unknown whether it has other uses] Fill a curve drawn in matrix mat, as 1's over a background of 0's, with 1's. p is V(i, j) of a point to fill from. dir is 1 or -1 for the standard recursive fill algorithm. Here is an explanation of how this is used and how it works then, by Huaicai: This function is used to fill the area between the rectangle bounding box and the boundary of the curve with 1's. The bounding box is extended by (lower left corner -2, right top corner + 2). The curve boundary is filled with 1's. So mat[1,:] = 0, mat[-1,:] = 0, mat[:, 1] = 0; mat[:, -1]=0, which means the area is connected. If we start from mat[1, 1], dir = 1, then we scan the first line from left to right. If it's 0, fill it as 1 until we touch 1. For each element in the line, we also check it's neighbor above and below. For the neighbor elements, if the neighbor touches 1 but previous neighbor is 0, then scan the neighbor line in the reverse order. I think this algorithm is better than the simple recursive flood filling algorithm. The seed mat[1, 1] is always inside the area, and most probably this filling area is smaller than that inside the curve. I think it also reduces repeated checking/filling of the classical algorithm. """ if mat[p]: return up = dn = 0 o1 = array([1, 0]) od = array([0, dir]) while not mat[p - od]: p -= od while not mat[p]: mat[p] = 1 if mat[p - o1]: if up: fill(mat, p - [1, dir], -dir) up = 0 else: up = 1 if mat[p + o1]: if dn: fill(mat, p + [1, -dir], -dir) dn = 0 else: dn = 1 p += od fill(mat, p - od + o1, -dir) fill(mat, p - od - o1, -dir) # note: we have (probably) seen recursion limit errors from this line. [bruce 070605 comment] #bruce 041214 made a common superclass for curve and rectangle classes, # so I can fix some bugs in a single place, and since there's a # lot of common code. Some of it could be moved into class shape (for more # efficiency when several curves in one shape), but I didn't do that, since # I'm not sure we'll always want to depend on that agreement of coord systems # for everything in one shape. class simple_shape_2d: """ common code for selection curve and selection rectangle; also used in CrystalShape.py """ def __init__(self, shp, ptlist, origin, selSense, opts): """ ptlist is a list of 3d points describing a selection (in a subclass-specific manner). origin is the center of view, and shp.normal gives the direction of the line of light. """ # store orthonormal screen-coordinates from shp self.right = shp.right self.up = shp.up self.normal = shp.normal # store other args self.ptlist = ptlist self.org = origin + 0.0 self.selSense = selSense self.slab = opts.get('slab', None) # how thick in what direction self.eyeball = opts.get('eye', None) # for projecting if not in ortho mode if self.eyeball: self.eye2Pov = vlen(self.org - self.eyeball) # project the (3d) path onto the plane. Warning: arbitrary 2d origin! # Note: original code used project_2d_noeyeball, and I think this worked # since the points were all in the same screen-parallel plane as # self.org (this is a guess), but it seems better to not require this # but just to use project_2d here (taking eyeball into account). self._computeBBox() def _computeBBox(self): """ Construct the 3d bounding box for the area """ # compute bounding rectangle (2d) self.pt2d = map( self.project_2d, self.ptlist) assert not (None in self.pt2d) self.bboxhi = reduce(maximum, self.pt2d) self.bboxlo = reduce(minimum, self.pt2d) bboxlo, bboxhi = self.bboxlo, self.bboxhi # compute 3d bounding box # Note: bboxlo, bboxhi are 2d coordinates relative to the on plane # 2D coordinate system: self.right and self.up. When constructing # the 3D bounding box, the coordinates will be transformed back to # 3d world coordinates. if self.slab: x, y = self.right, self.up self.bbox = BBox(V(bboxlo, bboxhi), V(x, y), self.slab) else: self.bbox = BBox() return def project_2d_noeyeball(self, pt): """ Bruce: Project a point into our plane (ignoring eyeball). Warning: arbitrary origin! Huaicai 4/20/05: This is just to project pt into a 2d coordinate system (self.right, self.up) on a plane through pt and parallel to the screen plane. For perspective projection, (x, y) on this plane is different than that on the plane through pov. """ x, y = self.right, self.up return V(dot(pt, x), dot(pt, y)) def project_2d(self, pt): """ like project_2d_noeyeball, but take into account self.eyeball; return None for a point that is too close to eyeball to be projected [in the future this might include anything too close to be drawn #e] """ p = self.project_2d_noeyeball(pt) if self.eyeball: # bruce 041214: use "pfix" to fix bug 30 comment #3 pfix = self.project_2d_noeyeball(self.org) p -= pfix try: ###e we recompute this a lot; should cache it in self or self.shp--Bruce ## Huaicai 04/23/05: made the change as suggested by Bruce above. p = p / (dot(pt - self.eyeball, self.normal) / self.eye2Pov) except: # bruce 041214 fix of unreported bug: # point is too close to eyeball for in-ness to be determined! # [More generally, do we want to include points which are # projectable without error, but too close to the eyeball # to be drawn? I think not, but I did not fix this yet # (or report the bug). ###e] if debug_flags.atom_debug: print_compact_traceback("atom_debug: ignoring math error for point near eyeball: ") return None p += pfix return p def isin_bbox(self, pt): """ say whether a point is in the optional slab, and 2d bbox (uses eyeball) """ # this is inlined and extended by curve.isin if self.slab and not self.slab.isin(pt): return False p = self.project_2d(pt) if p == None: return False return p[0]>=self.bboxlo[0] and p[1]>=self.bboxlo[1] \ and p[0]<=self.bboxhi[0] and p[1]<=self.bboxhi[1] pass # end of class simple_shape_2d class rectangle(simple_shape_2d): # bruce 041214 factored out simple_shape_2d """ selection rectangle """ def __init__(self, shp, pt1, pt2, origin, selSense, **opts): simple_shape_2d.__init__( self, shp, [pt1, pt2], origin, selSense, opts) def isin(self, pt): return self.isin_bbox(pt) def draw(self): """ Draw the rectangle """ color = get_selCurve_color(self.selSense) drawrectangle(self.ptlist[0], self.ptlist[1], self.right, self.up, color) pass class curve(simple_shape_2d): # bruce 041214 factored out simple_shape_2d """ Represents a single closed curve in 3-space, projected to a specified plane. """ def __init__(self, shp, ptlist, origin, selSense, **opts): """ ptlist is a list of 3d points describing a selection. origin is the center of view, and normal gives the direction of the line of light. Form a structure for telling whether arbitrary points fall inside the curve from the point of view. """ # bruce 041214 rewrote some of this method simple_shape_2d.__init__( self, shp, ptlist, origin, selSense, opts) # bounding rectangle, in integers (scaled 8 to the angstrom) ibbhi = array(map(int, ceil(8 * self.bboxhi)+2)) ibblo = array(map(int, floor(8 * self.bboxlo)-2)) bboxlo = self.bboxlo # draw the curve in these matrices and fill it # [bruce 041214 adds this comment: this might be correct but it's very # inefficient -- we should do it geometrically someday. #e] mat = zeros(ibbhi - ibblo) mat1 = zeros(ibbhi - ibblo) mat1[0,:] = 1 mat1[-1,:] = 1 mat1[:,0] = 1 mat1[:,-1] = 1 pt2d = self.pt2d pt0 = pt2d[0] for pt in pt2d[1:]: l = ceil(vlen(pt - pt0)*8) if l<0.01: continue v=(pt - pt0)/l for i in range(1 + int(l)): ij = 2 + array(map(int, floor((pt0 + v * i - bboxlo)*8))) mat[ij]=1 pt0 = pt mat1 += mat fill(mat1, array([1, 1]),1) mat1 -= mat #Which means boundary line is counted as inside the shape. # boolean raster of filled-in shape self.matrix = mat1 ## For any element inside the matrix, if it is 0, then it's inside. # where matrix[0, 0] is in x, y space self.matbase = ibblo # axes of the plane; only used for debugging self.x = self.right self.y = self.up self.z = self.normal def isin(self, pt): """ Project pt onto the curve's plane and return 1 if it falls inside the curve. """ # this inlines some of isin_bbox, since it needs an # intermediate value computed by that method if self.slab and not self.slab.isin(pt): return False p = self.project_2d(pt) if p == None: return False in_bbox = p[0]>=self.bboxlo[0] and p[1]>=self.bboxlo[1] \ and p[0]<=self.bboxhi[0] and p[1]<=self.bboxhi[1] if not in_bbox: return False ij = map(int, p * 8)-self.matbase return not self.matrix[ij] def xdraw(self): """ draw the actual grid of the matrix in 3-space. Used for debugging only. """ col = (0.0, 0.0, 0.0) dx = self.x/8.0 dy = self.y/8.0 for i in range(self.matrix.shape[0]): for j in range(self.matrix.shape[1]): if not self.matrix[i, j]: p = (V(i, j)+self.matbase)/8.0 p = p[0]*self.x + p[1]*self.y + self.z drawline(col, p, p + dx + dy) drawline(col, p + dx, p + dy) def draw(self): """ Draw two projections of the curve at the limits of the thickness that defines the crystal volume. The commented code is for debugging. [bruce 041214 adds comment: the code looks like it only draws one projection.] """ color = get_selCurve_color(self.selSense) pl = zip(self.ptlist[:-1],self.ptlist[1:]) for p in pl: drawline(color, p[0],p[1]) # for debugging #self.bbox.draw() #if self.eyeball: # for p in self.ptlist: # drawline(red, self.eyeball, p) #drawline(white, self.org, self.org + 10 * self.z) #drawline(white, self.org, self.org + 10 * self.x) #drawline(white, self.org, self.org + 10 * self.y) pass # end of class curve class shape: """ Represents a sequence of curves, each of which may be additive or subtractive. [This class should be renamed, since there is also an unrelated Numeric function called shape().] """ def __init__(self, right, up, normal): """ A shape is a set of curves defining the whole cutout. """ self.curves = [] self.bbox = BBox() # These arguments are required to be orthonormal: self.right = right self.up = up self.normal = normal def pickline(self, ptlist, origin, selSense, **xx): """ Add a new curve to the shape. Args define the curve (see curve) and the selSense operator for the curve telling whether it adds or removes material. """ c = curve(self, ptlist, origin, selSense, **xx) #self.curves += [c] #self.bbox.merge(c.bbox) return c def pickrect(self, pt1, pt2, org, selSense, **xx): c = rectangle(self, pt1, pt2, org, selSense, **xx) #self.curves += [c] #self.bbox.merge(c.bbox) return c def __str__(self): return "<Shape of " + `len(self.curves)` + ">" pass # end of class shape # == class SelectionShape(shape): # review: split this into its own file? [bruce 071215 Q] """ This is used to construct shape for atoms/chunks selection. A curve or rectangle will be created, which is used as an area selection of all the atoms/chunks """ def pickline(self, ptlist, origin, selSense, **xx): self.curve = shape.pickline(self, ptlist, origin, selSense, **xx) def pickrect(self, pt1, pt2, org, selSense, **xx): self.curve = shape.pickrect(self, pt1, pt2, org, selSense, **xx) def select(self, assy): """ Loop thru all the atoms that are visible and select any that are 'in' the shape, ignoring the thickness parameter. """ #bruce 041214 conditioned this on a.visible() to fix part of bug 235; # also added .hidden check to the last of 3 cases. Left everything else # as I found it. This code ought to be cleaned up to make it clear that # it uses the same way of finding the selection-set of atoms, for all # three selSense cases in each of select and partselect. If anyone adds # back any differences, this needs to be explained and justified in a # comment; lacking that, any such differences should be considered bugs. # # (BTW I don't know whether it's valid to care about selSense of only the # first curve in the shape, as this code does.) # Huaicai 04/23/05: For selection, every shape only has one curve, so # the above worry by Bruce is not necessary. The reason of not reusing # shape is because after each selection user may change view orientation, # which requires a new shape creation. if assy.selwhat: self._chunksSelect(assy) else: if self.curve.selSense == START_NEW_SELECTION: # New selection curve. Consistent with Select Chunks behavior. assy.unpickall_in_GLPane() # was unpickatoms and unpickparts [bruce 060721] ## assy.unpickparts() # Fixed bug 606, partial fix for bug 365. Mark 050713. ## assy.unpickatoms() # Fixed bug 1598. Mark 060303. self._atomsSelect(assy) def _atomsSelect(self, assy): """ Select all atoms inside the shape according to its selection selSense. """ c = self.curve if c.selSense == ADD_TO_SELECTION: for mol in assy.molecules: if mol.hidden: continue disp = mol.get_dispdef() for a in mol.atoms.itervalues(): if c.isin(a.posn()) and a.visible(disp): a.pick() elif c.selSense == START_NEW_SELECTION: for mol in assy.molecules: if mol.hidden: continue disp = mol.get_dispdef() for a in mol.atoms.itervalues(): if c.isin(a.posn()) and a.visible(disp): a.pick() else: a.unpick() elif c.selSense == SUBTRACT_FROM_SELECTION: for a in assy.selatoms.values(): if a.molecule.hidden: continue #bruce 041214 if c.isin(a.posn()) and a.visible(): a.unpick() elif c.selSense == DELETE_SELECTION: todo = [] for mol in assy.molecules: if mol.hidden: continue disp = mol.get_dispdef() for a in mol.atoms.itervalues(): if c.isin(a.posn()) and a.visible(disp): if a.is_singlet(): continue todo.append(a) for a in todo[:]: if a.filtered(): continue a.kill() else: print "Error in shape._atomsSelect(): Invalid selSense =", c.selSense #& debug method. mark 060211. def _chunksSelect(self, assy): """ Loop thru all the atoms that are visible and select any that are 'in' the shape, ignoring the thickness parameter. pick the parts that contain them """ #bruce 041214 conditioned this on a.visible() to fix part of bug 235; # also added .hidden check to the last of 3 cases. Same in self.select(). c = self.curve if c.selSense == START_NEW_SELECTION: # drag selection: unselect any selected Chunk not in the area, # modified by Huaicai to fix the selection bug 10/05/04 for m in assy.selmols[:]: m.unpick() if c.selSense == ADD_TO_SELECTION or c.selSense == START_NEW_SELECTION: for mol in assy.molecules: if mol.hidden: continue disp = mol.get_dispdef() for a in mol.atoms.itervalues(): if c.isin(a.posn()) and a.visible(disp): a.molecule.pick() break if c.selSense == SUBTRACT_FROM_SELECTION: for m in assy.selmols[:]: if m.hidden: continue #bruce 041214 disp = m.get_dispdef() for a in m.atoms.itervalues(): if c.isin(a.posn()) and a.visible(disp): m.unpick() break if c.selSense == DELETE_SELECTION: # mark 060220. todo = [] for mol in assy.molecules: if mol.hidden: continue disp = mol.get_dispdef() for a in mol.atoms.itervalues(): #bruce 060405 comment/bugfix: this use of itervalues looked dangerous (since mol was killed inside the loop), # but since the iterator is not continued after that, I suppose it was safe (purely a guess). # It would be safer (or more obviously safe) to build up a todo list of mols to kill after the loop. # More importantly, assy.molecules was not copied in the outer loop -- that could be a serious bug, # if it's incrementally modified. I'm fixing that now, using the todo list. if c.isin(a.posn()) and a.visible(disp): ## a.molecule.kill() todo.append(mol) #bruce 060405 bugfix break for mol in todo: mol.kill() return def findObjInside(self, assy): """ Find atoms/chunks that are inside the shape. """ rst = [] c = self.curve if assy.selwhat: ##Chunks rstMol = {} for mol in assy.molecules: if mol.hidden: continue disp = mol.get_dispdef() for a in mol.atoms.itervalues(): if c.isin(a.posn()) and a.visible(disp): rstMol[id(a.molecule)] = a.molecule break rst.extend(rstMol.itervalues()) else: ##Atoms for mol in assy.molecules: if mol.hidden: continue disp = mol.get_dispdef() for a in mol.atoms.itervalues(): if c.isin(a.posn()) and a.visible(disp): rst += [a] return rst pass # end of class SelectionShape # end
NanoCAD-master
cad/src/graphics/behaviors/shape.py
NanoCAD-master
cad/src/graphics/rendering/__init__.py
# Copyright 2004-2007 Nanorex, Inc. See LICENSE file for details. """ mdldata.py $Id$ """ filler = "0 0 1.10899\n"; marks = [(0.0017098087515823326, -1.0, -1.1903588901433509e-008) , (0.0012090115980704097, -1.0, -0.001209025283109241) , (-1.2261384241677788e-008, -1.0, -0.0017098087515823326) , (-0.001209025283109241, -1.0, -0.0012090115980704097) , (-0.0017098087515823326, -1.0, 1.2619111156727908e-008) , (-0.0012090115980704097, -1.0, 0.001209025283109241) , (1.1595538677340999e-008, -1.0, 0.0017098087515823326) , (0.001209025283109241, -1.0, 0.0012090115980704097) , (0.71013034999486813, -0.70710527589377681, 0.0) , (0.50213555030962398, -0.70710527589377681, -0.50213555030962398) , (5.3613123952239212e-008, -0.70710527589377681, -0.71013034999486813) , (-0.50213555030962398, -0.70710527589377681, -0.50213555030962398) , (-0.71013034999486813, -0.70710527589377681, -1.0722638475486675e-007) , (-0.50213623456156564, -0.70710527589377681, 0.50213555030962398) , (-3.3014677204146567e-007, -0.70710527589377681, 0.71013034999486813) , (0.50213555030962398, -0.70710527589377681, 0.50213623456156564) , (1.0, 0.0, 0.0) , (0.70710595641315144, 0.0, -0.70710595641315144) , (7.5498306476444628e-008, 0.0, -1.0) , (-0.70710595641315144, 0.0, -0.70710595641315144) , (-1.0, 0.0, -1.509959287009477e-007) , (-0.70710595641315144, 0.0, 0.70710595641315144) , (-4.6491361319237741e-007, 0.0, 1.0) , (0.70710595641315144, 0.0, 0.70710595641315144) , (0.71013034999486813, 0.70710527589377681, 0.0) , (0.50213623456156564, 0.70710527589377681, -0.50213623456156564) , (5.3613192377433375e-008, 0.70710527589377681, -0.71013034999486813) , (-0.50213623456156564, 0.70710527589377681, -0.50213623456156564) , (-0.71013034999486813, 0.70710527589377681, -1.0722638475486675e-007) , (-0.50213623456156564, 0.70710527589377681, 0.50213623456156564) , (-3.3014745629340725e-007, 0.70710527589377681, 0.71013034999486813) , (0.50213555030962398, 0.70710527589377681, 0.50213623456156564) , (0.0016114680625406274, 1.0, 1.1677169933969688e-008) , (0.0011394847582880017, 1.0, -0.0011394710732491704) , (1.1798829929179925e-008, 1.0, -0.0016114680625406274) , (-0.0011394710732491704, 1.0, -0.0011394847582880017) , (-0.0016114680625406274, 1.0, -1.1920489924390161e-008) , (-0.0011394847582880017, 1.0, 0.0011394710732491704) , (-1.242635738478908e-008, 1.0, 0.0016114680625406274) , (0.0011394710732491704, 1.0, 0.0011394847582880017)]; links = [19, 27, 35, 43, 51, 20, 28, 36, 44, 52, 21, 29, 37, 45, 53, 22, 30, 38, 46, 54, 23, 31, 39, 47, 55, 24, 32, 40, 48, 56, 25, 33, 41, 49, 57, 26, 34, 42, 50, 58] ; mdlheader = """[MODELFILE] ProductVersion=11.1 [POSTEFFECTS] [ENDPOSTEFFECTS] [IMAGES] [ENDIMAGES] [SOUNDS] [ENDSOUNDS] [MATERIALS] [ENDMATERIALS] [POSTEFFECTS] [ENDPOSTEFFECTS] [OBJECTS] [MODEL] [MESH] Version=2 """ mdlfooter = """[FileInfo] CreatedBy=NanoEngineer-1 Organization=Nanorex Url=www.nanorex.com Email=info@nanorex.com LastModifiedBy=NanoEngineer-1 [EndFileInfo] [ENDMODEL] [ENDOBJECTS] [ACTIONS] [ENDACTIONS] [CHOREOGRAPHIES] [ENDCHOREOGRAPHIES] [FileInfo] CreatedBy=NanoEngineer-1 Organization=Nanorex Url=www.nanorex.com Email=info@nanorex.com LastModifiedBy=NanoEngineer-1 [EndFileInfo] [ENDMODELFILE] """
NanoCAD-master
cad/src/graphics/rendering/mdl/mdldata.py
NanoCAD-master
cad/src/graphics/rendering/mdl/__init__.py
# Copyright 2004-2008 Nanorex, Inc. See LICENSE file for details. """ writemdlfile.py -- write a Part into an MDL (Animation Master Model) file (available from NE1's File -> Export menu) @author: Chris Phoenix and Mark Sims @version: $Id$ @copyright: 2004-2008 Nanorex, Inc. See LICENSE file for details. History: Bruce 080917 split this out of graphics/rendering/fileIO.py. For earlier history see that file's repository log. """ import math from geometry.VQT import A from graphics.rendering.mdl.mdldata import mdlheader from graphics.rendering.mdl.mdldata import mdlfooter from utilities.constants import diINVISIBLE # == # Create an MDL file - by Chris Phoenix and Mark for John Burch [04-12-03] # ninad060802 has disabled the File > Save As option to save the MDL file. (see bug 1508. Also, since in Alpha9 we will support OpenBabel, there will be a confusion between this MDL file format and the one that OpenBabel includes extension. If we support this filetype in future, its description field should be changed. def writemdlfile(part, glpane, filename): #bruce 050927 replaced assy argument with part and glpane args, added docstring """ write the given part into a new MDL file with the given name, using glpane.displayMode """ alist = [] #bruce 050325 changed assy.alist to localvar alist natoms = 0 # Specular values keyed by atom color # Only Carbon, Hydrogen and Silicon supported here specValues = {(117,117,117):((183, 183, 183), 16, 44), \ (256,256,256):((183, 183, 183), 15, 44), \ (111,93,133):((187,176,200), 16, 44)} # Determine the number of visible atoms in the part. # Invisible atoms are drawn. Hidden atoms are not drawn. # This is a bug to be fixed in the future. Will require work in chunk/chem.writemdl, too. # writepov may have this problem, too. # Mark [04-12-05] # To test this, we need to get a copy of Animation Master. # Mark [05-01-14] for mol in part.molecules: if (not mol.hidden) and (mol.display != diINVISIBLE): natoms += len(mol.atoms) #bruce 050421 disp->display (bugfix?) f = open(filename, 'w'); # Write the header f.write(mdlheader) # Write atoms with spline coordinates f.write("Splines=%d\n"%(13*natoms)) part.topnode.writemdl(alist, f, glpane.displayMode) #bruce 050421 changed assy.tree to assy.part.topnode to fix an assy/part bug #bruce 050927 changed assy.part -> new part arg # Write the GROUP information # Currently, each atom is f.write("[ENDMESH]\n[GROUPS]\n") atomindex = 0 for mol in part.molecules: col = mol.color # Color of molecule for a in mol.atoms.values(): # Begin GROUP record for this atom. f.write("[GROUP]\nName=Atom%d\nCount=80\n"%atomindex) # Write atom mesh IDs for j in range(80): f.write("%d\n"%(98-j+atomindex*80)) # Write Pivot record for this atom. # print "a.pos = ", a.posn() xyz=a.posn() n=(float(xyz[0]), float(xyz[1]), float(xyz[2])) f.write("Pivot= %f %f %f\n" % n) # Add DiffuseColor record for this atom. color = col or a.element.color # if this was color = a.drawing_color() it would mess up the specularity lookup below; # could be fixed somehow... [bruce 070417 comment] rgb=map(int,A(color)*255) # rgb = 3-tuple of int color=(int(rgb[0]), int(rgb[1]), int(rgb[2])) f.write("DiffuseColor=%d %d %d\n"%color) # Added specularity per John Burch's request # Specular values keyed by atom color (specColor, specSize, specIntensity) = \ specValues.get(color, ((183,183,183),16,44)) f.write("SpecularColor=%d %d %d\n"%specColor) f.write("SpecularSize=%d\n"%specSize) f.write("SpecularIntensity=%d\n"%specIntensity) # End the group for this atom. f.write("[ENDGROUP]\n") atomindex += 1 # ENDGROUPS f.write("[ENDGROUPS]\n") # Write the footer and close fpos = f.tell() f.write(mdlfooter) f.write("FileInfoPos=%d\n"%fpos) f.close() return # end
NanoCAD-master
cad/src/graphics/rendering/mdl/writemdlfile.py