def __init__(self, interestMgr, name, doneEvent=None, recurse=True, start=True, mustCollect=False, doCollectionMgr=None): DirectObject.__init__(self) self._interestMgr = interestMgr if doCollectionMgr is None: doCollectionMgr = interestMgr self._doCollectionMgr = doCollectionMgr self._eGroup = EventGroup(name, doneEvent=doneEvent) self._doneEvent = self._eGroup.getDoneEvent() self._gotEvent = False self._recurse = recurse if self._recurse: # this will hold a dict of parentId to set(zoneIds) that are closing self.closingParent2zones = {} if start: self.startCollect(mustCollect)
def _leak(self, task): self._leakers.append(DirectObject()) self._leakers[-1].accept(uniqueName('leak-msg-listeners'), self._leak) return task.cont
def _leak(self, task): self._leakers.append(DirectObject()) self._leakers[-1].accept('leak-msg', self._leak) return task.cont
def __init__(self, parent = None, **kw): # Inherits from DirectFrame # A Direct Frame can have: # - A background texture (pass in path to image, or Texture Card) # - A midground geometry item (pass in geometry) # - A foreground text Node (pass in text string or Onscreen Text) # For a direct entry: # Each button has 3 states (focus, noFocus, disabled) # The same image/geom/text can be used for all three states or each # state can have a different text/geom/image # State transitions happen automatically based upon mouse interaction optiondefs = ( # Define type of DirectGuiWidget ('pgFunc', PGEntry, None), ('numStates', 3, None), ('state', DGG.NORMAL, None), ('entryFont', None, DGG.INITOPT), ('width', 10, self.setup), ('numLines', 1, self.setup), ('focus', 0, self.setFocus), ('cursorKeys', 1, self.setCursorKeysActive), ('obscured', 0, self.setObscureMode), # Setting backgroundFocus allows the entry box to get keyboard # events that are not handled by other things (i.e. events that # fall through to the background): ('backgroundFocus', 0, self.setBackgroundFocus), # Text used for the PGEntry text node # NOTE: This overrides the DirectFrame text option ('initialText', '', DGG.INITOPT), # Command to be called on hitting Enter ('command', None, None), ('extraArgs', [], None), # Command to be called when enter is hit but we fail to submit ('failedCommand', None, None), ('failedExtraArgs',[], None), # commands to be called when focus is gained or lost ('focusInCommand', None, None), ('focusInExtraArgs', [], None), ('focusOutCommand', None, None), ('focusOutExtraArgs', [], None), # Sounds to be used for button events ('rolloverSound', DGG.getDefaultRolloverSound(), self.setRolloverSound), ('clickSound', DGG.getDefaultClickSound(), self.setClickSound), ('autoCapitalize', 0, self.autoCapitalizeFunc), ('autoCapitalizeAllowPrefixes', DirectEntry.AllowCapNamePrefixes, None), ('autoCapitalizeForcePrefixes', DirectEntry.ForceCapNamePrefixes, None), ) # Merge keyword options with default options self.defineoptions(kw, optiondefs) # Initialize superclasses DirectFrame.__init__(self, parent) if self['entryFont'] == None: font = DGG.getDefaultFont() else: font = self['entryFont'] # Create Text Node Component self.onscreenText = self.createcomponent( 'text', (), None, OnscreenText, (), parent = hidden, # Pass in empty text to avoid extra work, since its really # The PGEntry which will use the TextNode to generate geometry text = '', align = TextNode.ALeft, font = font, scale = 1, # Don't get rid of the text node mayChange = 1) # We can get rid of the node path since we're just using the # onscreenText as an easy way to access a text node as a # component self.onscreenText.removeNode() # Bind command function self.bind(DGG.ACCEPT, self.commandFunc) self.bind(DGG.ACCEPTFAILED, self.failedCommandFunc) self.accept(self.guiItem.getFocusInEvent(), self.focusInCommandFunc) self.accept(self.guiItem.getFocusOutEvent(), self.focusOutCommandFunc) # listen for auto-capitalize events on a separate object to prevent # clashing with other parts of the system self._autoCapListener = DirectObject() # Call option initialization functions self.initialiseoptions(DirectEntry) if not hasattr(self, 'autoCapitalizeAllowPrefixes'): self.autoCapitalizeAllowPrefixes = DirectEntry.AllowCapNamePrefixes if not hasattr(self, 'autoCapitalizeForcePrefixes'): self.autoCapitalizeForcePrefixes = DirectEntry.ForceCapNamePrefixes # Update TextNodes for each state for i in range(self['numStates']): self.guiItem.setTextDef(i, self.onscreenText.textNode) # Now we should call setup() again to make sure it has the # right font def. self.setup() # Update initial text self.unicodeText = 0 if self['initialText']: self.set(self['initialText'])
class DirectEntry(DirectFrame): """ DirectEntry(parent) - Create a DirectGuiWidget which responds to keyboard buttons """ directWtext = ConfigVariableBool('direct-wtext', 1) AllowCapNamePrefixes = ("Al", "Ap", "Ben", "De", "Del", "Della", "Delle", "Der", "Di", "Du", "El", "Fitz", "La", "Las", "Le", "Les", "Lo", "Los", "Mac", "St", "Te", "Ten", "Van", "Von", ) ForceCapNamePrefixes = ("D'", "DeLa", "Dell'", "L'", "M'", "Mc", "O'", ) def __init__(self, parent = None, **kw): # Inherits from DirectFrame # A Direct Frame can have: # - A background texture (pass in path to image, or Texture Card) # - A midground geometry item (pass in geometry) # - A foreground text Node (pass in text string or Onscreen Text) # For a direct entry: # Each button has 3 states (focus, noFocus, disabled) # The same image/geom/text can be used for all three states or each # state can have a different text/geom/image # State transitions happen automatically based upon mouse interaction optiondefs = ( # Define type of DirectGuiWidget ('pgFunc', PGEntry, None), ('numStates', 3, None), ('state', DGG.NORMAL, None), ('entryFont', None, DGG.INITOPT), ('width', 10, self.setup), ('numLines', 1, self.setup), ('focus', 0, self.setFocus), ('cursorKeys', 1, self.setCursorKeysActive), ('obscured', 0, self.setObscureMode), # Setting backgroundFocus allows the entry box to get keyboard # events that are not handled by other things (i.e. events that # fall through to the background): ('backgroundFocus', 0, self.setBackgroundFocus), # Text used for the PGEntry text node # NOTE: This overrides the DirectFrame text option ('initialText', '', DGG.INITOPT), # Command to be called on hitting Enter ('command', None, None), ('extraArgs', [], None), # Command to be called when enter is hit but we fail to submit ('failedCommand', None, None), ('failedExtraArgs',[], None), # commands to be called when focus is gained or lost ('focusInCommand', None, None), ('focusInExtraArgs', [], None), ('focusOutCommand', None, None), ('focusOutExtraArgs', [], None), # Sounds to be used for button events ('rolloverSound', DGG.getDefaultRolloverSound(), self.setRolloverSound), ('clickSound', DGG.getDefaultClickSound(), self.setClickSound), ('autoCapitalize', 0, self.autoCapitalizeFunc), ('autoCapitalizeAllowPrefixes', DirectEntry.AllowCapNamePrefixes, None), ('autoCapitalizeForcePrefixes', DirectEntry.ForceCapNamePrefixes, None), ) # Merge keyword options with default options self.defineoptions(kw, optiondefs) # Initialize superclasses DirectFrame.__init__(self, parent) if self['entryFont'] == None: font = DGG.getDefaultFont() else: font = self['entryFont'] # Create Text Node Component self.onscreenText = self.createcomponent( 'text', (), None, OnscreenText, (), parent = hidden, # Pass in empty text to avoid extra work, since its really # The PGEntry which will use the TextNode to generate geometry text = '', align = TextNode.ALeft, font = font, scale = 1, # Don't get rid of the text node mayChange = 1) # We can get rid of the node path since we're just using the # onscreenText as an easy way to access a text node as a # component self.onscreenText.removeNode() # Bind command function self.bind(DGG.ACCEPT, self.commandFunc) self.bind(DGG.ACCEPTFAILED, self.failedCommandFunc) self.accept(self.guiItem.getFocusInEvent(), self.focusInCommandFunc) self.accept(self.guiItem.getFocusOutEvent(), self.focusOutCommandFunc) # listen for auto-capitalize events on a separate object to prevent # clashing with other parts of the system self._autoCapListener = DirectObject() # Call option initialization functions self.initialiseoptions(DirectEntry) if not hasattr(self, 'autoCapitalizeAllowPrefixes'): self.autoCapitalizeAllowPrefixes = DirectEntry.AllowCapNamePrefixes if not hasattr(self, 'autoCapitalizeForcePrefixes'): self.autoCapitalizeForcePrefixes = DirectEntry.ForceCapNamePrefixes # Update TextNodes for each state for i in range(self['numStates']): self.guiItem.setTextDef(i, self.onscreenText.textNode) # Now we should call setup() again to make sure it has the # right font def. self.setup() # Update initial text self.unicodeText = 0 if self['initialText']: self.set(self['initialText']) def destroy(self): self.ignoreAll() self._autoCapListener.ignoreAll() DirectFrame.destroy(self) def setup(self): self.guiItem.setupMinimal(self['width'], self['numLines']) def setFocus(self): PGEntry.setFocus(self.guiItem, self['focus']) def setCursorKeysActive(self): PGEntry.setCursorKeysActive(self.guiItem, self['cursorKeys']) def setObscureMode(self): PGEntry.setObscureMode(self.guiItem, self['obscured']) def setBackgroundFocus(self): PGEntry.setBackgroundFocus(self.guiItem, self['backgroundFocus']) def setRolloverSound(self): rolloverSound = self['rolloverSound'] if rolloverSound: self.guiItem.setSound(DGG.ENTER + self.guiId, rolloverSound) else: self.guiItem.clearSound(DGG.ENTER + self.guiId) def setClickSound(self): clickSound = self['clickSound'] if clickSound: self.guiItem.setSound(DGG.ACCEPT + self.guiId, clickSound) else: self.guiItem.clearSound(DGG.ACCEPT + self.guiId) def commandFunc(self, event): if self['command']: # Pass any extra args to command apply(self['command'], [self.get()] + self['extraArgs']) def failedCommandFunc(self, event): if self['failedCommand']: # Pass any extra args apply(self['failedCommand'], [self.get()] + self['failedExtraArgs']) def autoCapitalizeFunc(self): if self['autoCapitalize']: self._autoCapListener.accept(self.guiItem.getTypeEvent(), self._handleTyping) self._autoCapListener.accept(self.guiItem.getEraseEvent(), self._handleErasing) else: self._autoCapListener.ignore(self.guiItem.getTypeEvent()) self._autoCapListener.ignore(self.guiItem.getEraseEvent()) def focusInCommandFunc(self): if self['focusInCommand']: apply(self['focusInCommand'], self['focusInExtraArgs']) if self['autoCapitalize']: self.accept(self.guiItem.getTypeEvent(), self._handleTyping) self.accept(self.guiItem.getEraseEvent(), self._handleErasing) def _handleTyping(self, guiEvent): self._autoCapitalize() def _handleErasing(self, guiEvent): self._autoCapitalize() def _autoCapitalize(self): name = self.get().decode('utf-8') # capitalize each word, allowing for things like McMutton capName = '' # track each individual word to detect prefixes like Mc wordSoFar = '' # track whether the previous character was part of a word or not wasNonWordChar = True for i in xrange(len(name)): character = name[i] # test to see if we are between words # - Count characters that can't be capitalized as a break between words # This assumes that string.lower and string.upper will return different # values for all unicode letters. # - Don't count apostrophes as a break between words if ((string.lower(character) == string.upper(character)) and (character != "'")): # we are between words wordSoFar = '' wasNonWordChar = True else: capitalize = False if wasNonWordChar: # first letter of a word, capitalize it unconditionally; capitalize = True elif (character == string.upper(character) and len(self.autoCapitalizeAllowPrefixes) and wordSoFar in self.autoCapitalizeAllowPrefixes): # first letter after one of the prefixes, allow it to be capitalized capitalize = True elif (len(self.autoCapitalizeForcePrefixes) and wordSoFar in self.autoCapitalizeForcePrefixes): # first letter after one of the force prefixes, force it to be capitalized capitalize = True if capitalize: # allow this letter to remain capitalized character = string.upper(character) else: character = string.lower(character) wordSoFar += character wasNonWordChar = False capName += character self.enterText(capName.encode('utf-8')) def focusOutCommandFunc(self): if self['focusOutCommand']: apply(self['focusOutCommand'], self['focusOutExtraArgs']) if self['autoCapitalize']: self.ignore(self.guiItem.getTypeEvent()) self.ignore(self.guiItem.getEraseEvent()) def set(self, text): """ Changes the text currently showing in the typable region; does not change the current cursor position. Also see enterText(). """ self.unicodeText = isinstance(text, types.UnicodeType) if self.unicodeText: self.guiItem.setWtext(text) else: self.guiItem.setText(text) def get(self, plain = False): """ Returns the text currently showing in the typable region. If plain is True, the returned text will not include any formatting characters like nested color-change codes. """ wantWide = self.unicodeText or self.guiItem.isWtext() if not self.directWtext.getValue(): # If the user has configured wide-text off, then always # return an 8-bit string. This will be encoded if # necessary, according to Panda's default encoding. wantWide = False if plain: if wantWide: return self.guiItem.getPlainWtext() else: return self.guiItem.getPlainText() else: if wantWide: return self.guiItem.getWtext() else: return self.guiItem.getText() def setCursorPosition(self, pos): if (pos < 0): self.guiItem.setCursorPosition(self.guiItem.getNumCharacters() + pos) else: self.guiItem.setCursorPosition(pos) def enterText(self, text): """ sets the entry's text, and moves the cursor to the end """ self.set(text) self.setCursorPosition(self.guiItem.getNumCharacters()) def getFont(self): return self.onscreenText.getFont() def getBounds(self, state = 0): # Compute the width and height for the entry itself, ignoring # geometry etc. tn = self.onscreenText.textNode mat = tn.getTransform() align = tn.getAlign() lineHeight = tn.getLineHeight() numLines = self['numLines'] width = self['width'] if align == TextNode.ALeft: left = 0.0 right = width elif align == TextNode.ACenter: left = -width / 2.0 right = width / 2.0 elif align == TextNode.ARight: left = -width right = 0.0 bottom = -0.3 * lineHeight - (lineHeight * (numLines - 1)) top = lineHeight self.ll.set(left, 0.0, bottom) self.ur.set(right, 0.0, top) self.ll = mat.xformPoint(self.ll) self.ur = mat.xformPoint(self.ur) # Scale bounds to give a pad around graphics. We also want to # scale around the border width. pad = self['pad'] borderWidth = self['borderWidth'] self.bounds = [self.ll[0] - pad[0] - borderWidth[0], self.ur[0] + pad[0] + borderWidth[0], self.ll[2] - pad[1] - borderWidth[1], self.ur[2] + pad[1] + borderWidth[1]] return self.bounds
def __init__(self, name, parent_node_path): DirectObject.__init__(self) NodePath.__init__(self, name) # required initialization self.active = True self.enable = True self.pause = False self.pause_time = 0.0 self.fade = False self.fade_end = False self.fade_start_time = 0.0 self.fade_color_scale = 1.0 self.total_vertices = 0 self.last_update_time = 0.0 self.texture = None self.vertex_list = [] self.frame_list = [] self.parent_node_path = parent_node_path self.previous_matrix = None self.calculate_relative_matrix = False self.playing = False # default options self.continuous_motion_trail = True self.color_scale = 1.0 self.time_window = 1.0 self.sampling_time = 0.0 self.square_t = True # self.task_transform = False self.root_node_path = None # node path states self.reparentTo(parent_node_path) self.geom_node = GeomNode("motion_trail") self.geom_node_path = self.attachNewNode(self.geom_node) node_path = self.geom_node_path ### set render states node_path.setTwoSided(True) # set additive blend effects OTPRender.setAdditiveEffect(node_path, 'motion_trail') if (MotionTrail.task_added == False): # taskMgr.add (self.motion_trail_task, "motion_trail_task", priority = 50) taskMgr.add(self.motion_trail_task, MotionTrail.motion_trail_task_name) self.acceptOnce("clientLogout", remove_task) MotionTrail.task_added = True self.relative_to_render = False self.use_nurbs = False self.resolution_distance = 0.5 self.cmotion_trail = CMotionTrail() self.cmotion_trail.setGeomNode(self.geom_node) self.modified_vertices = True if base.config.GetBool('want-python-motion-trails', 0): self.use_python_version = True else: self.use_python_version = False return
def __init__(self, gsg=None, limit=None): DirectObject.__init__(self) # First, we'll need a name to uniquify the object. self.name = 'tex-mem%s' % (TexMemWatcher.NextIndex) TexMemWatcher.NextIndex += 1 self.cleanedUp = False self.top = 1.0 # The textures managed by the TexMemWatcher are packed # arbitrarily into the canvas, which is the viewable region # that represents texture memory allocation. The packing # arrangement has no relation to actual layout within texture # memory (which we have no way to determine). # The visual size of each texture is chosen in proportion to # the total number of bytes of texture memory the texture # consumes. This includes mipmaps, and accounts for texture # compression. Visually, a texture with mipmaps will be # represented by a rectangle 33% larger than an # equivalent-sized texture without mipmaps. Of course, this # once again has little bearing to the way the textures are # actually arranged in memory; but it serves to give a visual # indication of how much texture memory each texture consumes. # There is an arbitrary limit, self.limit, which may have been # passed to the constructor, or which may be arbitrarily # determined. This represents the intended limit to texture # memory utilization. We (generously) assume that the # graphics card will implement a perfect texture packing # algorithm, so that as long as our total utilization <= # self.limit, it must fit within texture memory. We represent # this visually by aggressively packing textures within the # self.limit block so that they are guaranteed to fit, as long # as we do not exceed the total utilization. This may # sometimes mean distorting a texture block or even breaking # it into multiple pieces to get it to fit, clearly # fictionalizing whatever the graphics driver is actually # doing. # Internally, textures are packed into an integer grid of # Q-units. Q-units are in proportion to texture bytes. # Specifically, each Q-unit corresponds to a block of # self.quantize * self.quantize texture bytes in the Texture # Memory window. The Q-units are the smallest packable unit; # increasing self.quantize therefore reduces the visual # packing resolution correspondingly. Q-units very roughly # correspond to pixels onscreen (they may be larger, sometimes # considerably larger, than 1 pixel, depending on the window # size). # This number defines the size of a Q-unit square, in texture # bytes. It is automatically adjusted in repack() based on # the window size and the texture memory size. self.quantize = 1 # This is the maximum number of bitmask rows (within # self.limit) to allocate for packing. This controls the # value assigned to self.quantize in repack(). self.maxHeight = base.config.GetInt('tex-mem-max-height', 300) # The total number of texture bytes tracked, including overflow. self.totalSize = 0 # The total number of texture bytes placed, not including # overflow (that is, within self.limit). self.placedSize = 0 # The total number of Q-units placed, not including overflow. self.placedQSize = 0 # If no GSG is specified, use the main GSG. if gsg is None: gsg = base.win.getGsg() elif isinstance(gsg, GraphicsOutput): # If we were passed a window, use that window's GSG. gsg = gsg.getGsg() self.gsg = gsg # Now open a new window just to render the output. size = ConfigVariableInt('tex-mem-win-size', '300 300') origin = ConfigVariableInt('tex-mem-win-origin', '100 100') self.winSize = (size[0], size[1]) name = 'Texture Memory' props = WindowProperties() props.setOrigin(origin[0], origin[1]) props.setSize(*self.winSize) props.setTitle(name) props.setFullscreen(False) props.setUndecorated(False) fbprops = FrameBufferProperties.getDefault() flags = GraphicsPipe.BFFbPropsOptional | GraphicsPipe.BFRequireWindow self.pipe = None # Set this to tinydisplay if you're running on a machine with # limited texture memory. That way you won't compete for # texture memory with the main scene. moduleName = base.config.GetString('tex-mem-pipe', '') if moduleName: self.pipe = base.makeModulePipe(moduleName) # If the requested pipe fails for some reason, we'll use the # regular pipe. if not self.pipe: self.pipe = base.pipe self.win = base.graphicsEngine.makeOutput(self.pipe, name, 0, fbprops, props, flags) assert self.win # We should render at the end of the frame. self.win.setSort(10000) # We don't need to clear the color buffer, since we'll be # filling it with a texture. We also don't need to clear the # depth buffer, since we won't be using it. self.win.setClearColorActive(False) self.win.setClearDepthActive(False) eventName = '%s-window' % (self.name) self.win.setWindowEvent(eventName) self.accept(eventName, self.windowEvent) # Listen for this event so we can update appropriately, if # anyone changes the window's graphics memory limit, self.accept('graphics_memory_limit_changed', self.graphicsMemoryLimitChanged) # We'll need a mouse object to get mouse events. self.mouse = base.dataRoot.attachNewNode( MouseAndKeyboard(self.win, 0, '%s-mouse' % (self.name))) bt = ButtonThrower('%s-thrower' % (self.name)) self.mouse.attachNewNode(bt) bt.setPrefix('button-%s-' % (self.name)) self.accept('button-%s-mouse1' % (self.name), self.mouseClick) self.setupGui() self.setupCanvas() # Now start handling up the actual stuff in the scene. self.background = None self.nextTexRecordKey = 0 self.rollover = None self.isolate = None self.isolated = None self.needsRepack = False # How frequently should the texture memory window check for # state changes? updateInterval = base.config.GetDouble("tex-mem-update-interval", 0.5) self.task = taskMgr.doMethodLater(updateInterval, self.updateTextures, 'TexMemWatcher') self.setLimit(limit)
def __init__ (self,name,parent_node_path): DirectObject.__init__(self) NodePath.__init__ (self,name) # required initialization self.active = True self.enable = True self.pause = False self.pause_time = 0.0 self.fade = False self.fade_end = False self.fade_start_time = 0.0 self.fade_color_scale = 1.0 self.total_vertices = 0 self.last_update_time = 0.0 self.texture = None self.vertex_list = [ ] self.frame_list = [ ] self.parent_node_path = parent_node_path self.previous_matrix = None self.calculate_relative_matrix = False self.playing = False; # default options self.continuous_motion_trail = True self.color_scale = 1.0 self.time_window = 1.0 self.sampling_time = 0.0 self.square_t = True # self.task_transform = False self.root_node_path = None # node path states self.reparentTo (parent_node_path) self.geom_node = GeomNode ("motion_trail") self.geom_node_path = self.attachNewNode(self.geom_node) node_path = self.geom_node_path ### set render states node_path.setTwoSided (True) # set additive blend effects OTPRender.setAdditiveEffect (node_path, 'motion_trail') if (MotionTrail.task_added == False): # taskMgr.add (self.motion_trail_task, "motion_trail_task", priority = 50) taskMgr.add (self.motion_trail_task, MotionTrail.motion_trail_task_name) self.acceptOnce ("clientLogout", remove_task) MotionTrail.task_added = True self.relative_to_render = False self.use_nurbs = False self.resolution_distance = 0.5 self.cmotion_trail = CMotionTrail ( ) self.cmotion_trail.setGeomNode (self.geom_node) self.modified_vertices = True if base.config.GetBool('want-python-motion-trails', 0): self.use_python_version = True else: self.use_python_version = False return
def __init__(self, **kargs): DirectObject.__init__(self) self.handlers = {}
def __init__(self, gsg = None, limit = None): DirectObject.__init__(self) # First, we'll need a name to uniquify the object. self.name = 'tex-mem%s' % (TexMemWatcher.NextIndex) TexMemWatcher.NextIndex += 1 self.cleanedUp = False self.top = 1.0 # The textures managed by the TexMemWatcher are packed # arbitrarily into the canvas, which is the viewable region # that represents texture memory allocation. The packing # arrangement has no relation to actual layout within texture # memory (which we have no way to determine). # The visual size of each texture is chosen in proportion to # the total number of bytes of texture memory the texture # consumes. This includes mipmaps, and accounts for texture # compression. Visually, a texture with mipmaps will be # represented by a rectangle 33% larger than an # equivalent-sized texture without mipmaps. Of course, this # once again has little bearing to the way the textures are # actually arranged in memory; but it serves to give a visual # indication of how much texture memory each texture consumes. # There is an arbitrary limit, self.limit, which may have been # passed to the constructor, or which may be arbitrarily # determined. This represents the intended limit to texture # memory utilization. We (generously) assume that the # graphics card will implement a perfect texture packing # algorithm, so that as long as our total utilization <= # self.limit, it must fit within texture memory. We represent # this visually by aggressively packing textures within the # self.limit block so that they are guaranteed to fit, as long # as we do not exceed the total utilization. This may # sometimes mean distorting a texture block or even breaking # it into multiple pieces to get it to fit, clearly # fictionalizing whatever the graphics driver is actually # doing. # Internally, textures are packed into an integer grid of # Q-units. Q-units are in proportion to texture bytes. # Specifically, each Q-unit corresponds to a block of # self.quantize * self.quantize texture bytes in the Texture # Memory window. The Q-units are the smallest packable unit; # increasing self.quantize therefore reduces the visual # packing resolution correspondingly. Q-units very roughly # correspond to pixels onscreen (they may be larger, sometimes # considerably larger, than 1 pixel, depending on the window # size). # This number defines the size of a Q-unit square, in texture # bytes. It is automatically adjusted in repack() based on # the window size and the texture memory size. self.quantize = 1 # This is the maximum number of bitmask rows (within # self.limit) to allocate for packing. This controls the # value assigned to self.quantize in repack(). self.maxHeight = base.config.GetInt('tex-mem-max-height', 300) # The total number of texture bytes tracked, including overflow. self.totalSize = 0 # The total number of texture bytes placed, not including # overflow (that is, within self.limit). self.placedSize = 0 # The total number of Q-units placed, not including overflow. self.placedQSize = 0 # If no GSG is specified, use the main GSG. if gsg is None: gsg = base.win.getGsg() elif isinstance(gsg, GraphicsOutput): # If we were passed a window, use that window's GSG. gsg = gsg.getGsg() self.gsg = gsg # Now open a new window just to render the output. size = ConfigVariableInt('tex-mem-win-size', '300 300') origin = ConfigVariableInt('tex-mem-win-origin', '100 100') self.winSize = (size[0], size[1]) name = 'Texture Memory' props = WindowProperties() props.setOrigin(origin[0], origin[1]) props.setSize(*self.winSize) props.setTitle(name) props.setFullscreen(False) props.setUndecorated(False) fbprops = FrameBufferProperties.getDefault() flags = GraphicsPipe.BFFbPropsOptional | GraphicsPipe.BFRequireWindow self.pipe = None # Set this to tinydisplay if you're running on a machine with # limited texture memory. That way you won't compete for # texture memory with the main scene. moduleName = base.config.GetString('tex-mem-pipe', '') if moduleName: self.pipe = base.makeModulePipe(moduleName) # If the requested pipe fails for some reason, we'll use the # regular pipe. if not self.pipe: self.pipe = base.pipe self.win = base.graphicsEngine.makeOutput(self.pipe, name, 0, fbprops, props, flags) assert self.win # We should render at the end of the frame. self.win.setSort(10000) # We don't need to clear the color buffer, since we'll be # filling it with a texture. We also don't need to clear the # depth buffer, since we won't be using it. self.win.setClearColorActive(False) self.win.setClearDepthActive(False) eventName = '%s-window' % (self.name) self.win.setWindowEvent(eventName) self.accept(eventName, self.windowEvent) # Listen for this event so we can update appropriately, if # anyone changes the window's graphics memory limit, self.accept('graphics_memory_limit_changed', self.graphicsMemoryLimitChanged) # We'll need a mouse object to get mouse events. self.mouse = base.dataRoot.attachNewNode(MouseAndKeyboard(self.win, 0, '%s-mouse' % (self.name))) bt = ButtonThrower('%s-thrower' % (self.name)) self.mouse.attachNewNode(bt) bt.setPrefix('button-%s-' % (self.name)) self.accept('button-%s-mouse1' % (self.name), self.mouseClick) self.setupGui() self.setupCanvas() # Now start handling up the actual stuff in the scene. self.background = None self.nextTexRecordKey = 0 self.rollover = None self.isolate = None self.isolated = None self.needsRepack = False # How frequently should the texture memory window check for # state changes? updateInterval = base.config.GetDouble("tex-mem-update-interval", 0.5) self.task = taskMgr.doMethodLater(updateInterval, self.updateTextures, 'TexMemWatcher') self.setLimit(limit)