def __init__(self): """ constructor """ ObjectManager.__init__(self) self.setters.update({ 'name' : 'set_general', 'ac_check_methods' : 'set_many', 'acl' : 'set_acl', }) self.getters.update({ 'name' : 'get_general', 'ac_check_methods' : 'get_many_to_many', 'acl' : 'get_acl', }) self.my_django_model = facade.models.Role
def __init__(self): """ constructor """ ObjectManager.__init__(self) self.setters.update({ 'name': 'set_general', 'ac_check_methods': 'set_many', 'acl': 'set_acl', }) self.getters.update({ 'name': 'get_general', 'ac_check_methods': 'get_many_to_many', 'acl': 'get_acl', }) self.my_django_model = facade.models.Role
def __init__(self): """ constructor """ ObjectManager.__init__(self) self.getters.update({ 'text': 'get_general', }) self.setters.update({ 'text': 'set_general', }) # We don't allow Notes about Notes, but it would be a lot funnier if we did if self.getters.has_key('notes'): del self.getters['notes'] if self.getters.has_key('notes'): del self.setters['notes'] self.my_django_model = facade.models.Note
def __init__(self): """ constructor """ ObjectManager.__init__(self) self.getters.update({ 'text' : 'get_general', }) self.setters.update({ 'text' : 'set_general', }) # We don't allow Notes about Notes, but it would be a lot funnier if we did if self.getters.has_key('notes'): del self.getters['notes'] if self.getters.has_key('notes'): del self.setters['notes'] self.my_django_model = facade.models.Note
def new_blank_object_manager(self): object_manager = ObjectManager( fp_name="", default_clearance=UnitNumber(DEFAULT_DEFAULT_CLEARANCE_MILS, 'mil'), default_mask=UnitNumber(DEFAULT_DEFAULT_MASK_MILS, 'mil')) CenterPoint.new(object_manager) return object_manager
def __init__(self, name=str(uuid4())): # PCCs to be calculated only if it is in Master Mode. self.calculate_pcc = True # Unique ID for this dataframe. self.name = name # The object that deals with type management self.type_manager = TypeManager() # The object that deals with object management self.object_manager = ObjectManager(self.type_manager) # The object that deals with record management self.change_manager = ChangeManager() # Flag to see if the dataframe should keep a record of all changes. # Can be used to synchnronize between dataframes. self.start_recording = False
def __init__(self, globalStates: GlobalStates): self.globalStates = globalStates self._levelsWaitingObj_l = [] self._levels_l = [] self._watingForLevel_i = 0 self._fromLevelLoaderQueue = Queue() self._toLevelLoaderQueue = Queue() self._levelLoader = LevelLoader(self._fromLevelLoaderQueue, self._toLevelLoaderQueue) self._objectMan = ObjectManager() self.overlayUiMan = OverlayUiManager(self._objectMan.texMan, self.globalStates) self.console = self.overlayUiMan.consoleWin self._objectMan.console = self.console
def new(cls): self = cls() self.show() self.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.KEY_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK) self.connect("button-press-event", cls.click_event) self.connect("button-release-event", cls.release_event) self.connect("expose-event", cls.expose_event) self.connect("motion-notify-event", cls.motion_notify_event) self.connect("configure-event", cls.configure_event) self.connect("key-press-event", cls.key_press_event) self.connect("scroll-event", cls.scroll_event) # Where we last saw the mouse. self.x = 0 self.y = 0 # Offsets for converting between screen coordinates and logical # coordinates. self.scale_x = 100 self.scale_y = 100 # How far zoomed we are. Higher numbers mean more zoomed in. self.scale_factor = 1 self.pixmap = None # Whether we're currently in the middle of a drag. self.dragging = False self.object_manager = ObjectManager() self.active_object = None self.dragging_object = None self.selected_primitives = set() # Create the center point p = CenterPoint(self.object_manager, set()) self.object_manager.add_primitive(p) self.deselect_all() return self
class dataframe(object): # Control Flows for dataframe #.1 Type Management ##.1a Adding a type ##.1b Reloading a type ##.1c Deleting a type #.2 Object Management ##.2a Adding objects of type ##.2b Calculating dependent pure types from any change. (Master type only) ##.2c Calculating pure dependent types. ##.2d Get objects of type ##.2e Track changes to objects ###.2ea Uses 3a ##.f Delete objects #.3 Record Management ##.3a Record changes to objects. ##.3b Clear changes to objects. ##.3c Allow object serialization to records. ##.3d Record buffers (new, mod, and deleted). ##.3e clear buffers def __init__(self, name=str(uuid4())): # PCCs to be calculated only if it is in Master Mode. self.calculate_pcc = True # Unique ID for this dataframe. self.name = name # The object that deals with type management self.type_manager = TypeManager() # The object that deals with object management self.object_manager = ObjectManager(self.type_manager) # The object that deals with record management self.change_manager = ChangeManager() # Flag to see if the dataframe should keep a record of all changes. # Can be used to synchnronize between dataframes. self.start_recording = False ####### TYPE MANAGEMENT METHODS ############# def add_type(self, tp, tracking=False): pairs_added = self.type_manager.add_type( tp, tracking, self.object_manager.adjust_pcc, self.change_manager.report_dim_modification, self.object_manager.create_records_for_dim_modification) self.object_manager.create_tables(pairs_added) def add_types(self, types, tracking=False): pairs_added = self.type_manager.add_types( types, tracking, self.object_manager.adjust_pcc, self.change_manager.report_dim_modification, self.object_manager.create_records_for_dim_modification) self.object_manager.create_tables(pairs_added) def has_type(self, tp): self.type_manager.has_types(tp) def reload_types(self, types): # TODO self.type_manager.reload_types(types) def remove_type(self, tp): # TODO self.type_manager.remove_type(tp) def remove_types(self, types): # TODO self.type_manager.remove_types(types) ############################################# ####### OBJECT MANAGEMENT METHODS ########### def append(self, tp, obj): if (self.type_manager.check_for_new_insert(tp) and self.type_manager.check_obj_type_for_insert(tp, obj)): tp_obj = self.type_manager.get_requested_type(tp) records = self.object_manager.append(tp_obj, obj) self.change_manager.add_records(records) def extend(self, tp, objs): if (self.type_manager.check_for_new_insert(tp)): tp_obj = self.type_manager.get_requested_type(tp) for obj in objs: # One pass through objects to see if the types match. self.type_manager.check_obj_type_for_insert(tp, obj) records = self.object_manager.extend(tp_obj, objs) self.change_manager.add_records(records) def get(self, tp, oid=None, parameters=None): # TODO: Add checks for tp if tp.__realname__ not in self.type_manager.observing_types: raise TypeError("%s Type is not registered for observing." % tp.__realname__) tp_obj = self.type_manager.get_requested_type(tp) return self.object_manager.get( tp_obj, parameters) if oid == None else self.object_manager.get_one( tp_obj, oid, parameters) def delete(self, tp, obj): # TODO: Add checks for tp tp_obj = self.type_manager.get_requested_type(tp) records = self.object_manager.delete(tp_obj, obj) self.change_manager.add_records(records) def delete_all(self, tp): # TODO: Add checks for tp tp_obj = self.type_manager.get_requested_type(tp) records = self.object_manager.delete_all(tp_obj) self.change_manager.add_records(records) def clear_joins(self): for tp_obj in self.type_manager.get_join_types(): _ = self.object_manager.delete_all(tp_obj) ############################################# ####### CHANGE MANAGEMENT METHODS ########### @property def start_recording(self): return self.change_manager.startrecording @start_recording.setter def start_recording(self, v): self.change_manager.startrecording = v def apply_changes(self, changes, except_app=None, track=True): if "gc" not in changes: return applied_records, pcc_change_records, deletes = self.object_manager.apply_changes( changes) self.object_manager.add_buffer_changes(changes, deletes) if track: self.change_manager.add_records(applied_records, pcc_change_records, except_app) def get_record(self): return self.change_manager.get_record() def clear_record(self): return self.change_manager.clear_record() def connect_app_queue(self, app_queue): return self.type_manager.get_impures_in_types( app_queue.types), self.change_manager.add_app_queue(app_queue) def convert_to_record(self, results, deleted_oids): return self.object_manager.convert_to_records(results, deleted_oids) def serialize_all(self): return self.change_manager.convert_to_serializable_dict( self.object_manager.convert_whole_object_map()) def get_new(self, tp): return self.object_manager.get_new(tp) def get_mod(self, tp): return self.object_manager.get_mod(tp) def get_deleted(self, tp): return self.object_manager.get_deleted(tp) def clear_all(self): return self.object_manager.clear_all() def clear_buffer(self): return self.object_manager.clear_buffer()
def undo(self): self._redo_list.append(self._undo_list.pop()) (last_fp, last_modified) = self._undo_list[-1] new_object_manager = ObjectManager.from_dict(last_fp) self.set_object_manager(new_object_manager) self.emit("modified", last_modified)
def load_file(self, filename): with open(filename) as f: contents = f.read() d = json.loads(contents) new_object_manager = ObjectManager.from_dict(d) self.fparea.set_object_manager(new_object_manager)
class ResourceManager: def __init__(self, globalStates: GlobalStates): self.globalStates = globalStates self._levelsWaitingObj_l = [] self._levels_l = [] self._watingForLevel_i = 0 self._fromLevelLoaderQueue = Queue() self._toLevelLoaderQueue = Queue() self._levelLoader = LevelLoader(self._fromLevelLoaderQueue, self._toLevelLoaderQueue) self._objectMan = ObjectManager() self.overlayUiMan = OverlayUiManager(self._objectMan.texMan, self.globalStates) self.console = self.overlayUiMan.consoleWin self._objectMan.console = self.console def renderAll(self, uniLoc: UniformLocs) -> None: for level in self._levels_l: level.renderAll(uniLoc) gl.glDisable(gl.GL_CULL_FACE) gl.glDisable(gl.GL_DEPTH_TEST) self.overlayUiMan.render() def resize(self): self.overlayUiMan.resize() def renderShadow(self, uniLocShadow) -> None: for level in self._levels_l: level.renderShadow(uniLocShadow) def levelsGen(self) -> Generator[Level, None, None]: for level in self._levels_l: yield level def terminate(self) -> None: self._objectMan.terminate() for level in self._levels_l: objTempNames_l = level.terminate() self._objectMan.dumpObjects(objTempNames_l) del self._levels_l, self._levelsWaitingObj_l try: self._levelLoader.terminate() except AttributeError: pass def runProcesses(self) -> None: self._levelLoader.start() self._objectMan.runProcesses() def update(self) -> None: self.__popFromLevelLoader() self.__fillLevelWithObjects() def findLevelByName(self, levelName_s: str) -> Optional[Level]: for level in self._levels_l: if level.getName() == levelName_s: return level else: return None def findObjectInLevelByName(self, levelName_s: str, objectName_s: str) -> Optional[Object]: level = self.findLevelByName(levelName_s) if level is None: return None else: return level.findObjectByName(objectName_s) def requestLevelLoad(self, levelName_s: str, waitTime_f: float = 0.0) -> None: for level in self._levels_l: if level.getName() == levelName_s: print("Already loaded level:", levelName_s) self.console.appendLogs( "Already loaded level: '{}'".format(levelName_s)) break else: smllFileDir_s = self.__findLevelDir(levelName_s + ".smll") self._toLevelLoaderQueue.put(smllFileDir_s) self._watingForLevel_i += 1 if waitTime_f <= 0.0: return waitStartTime_f = time() while time() - waitStartTime_f < waitTime_f: self.update() if self.getLevelWithNameInLevelsList(levelName_s) is None: continue else: if self.getLevelWithNameInLevelWaitingObjList( levelName_s) is None: continue else: return else: raise FileNotFoundError("Level loading time out") def deleteLevel(self, levelName_s: str) -> None: for x, level in enumerate(self._levels_l): if level.getName() == levelName_s: del self._levels_l[x] self._objectMan.dumpObjects(level.terminate()) for x, level in enumerate(self._levelsWaitingObj_l): if level.getName() == levelName_s: del self._levels_l[x] def deleteAllLevels(self): for x in range(len(self._levels_l) - 1, -1, -1): level = self._levels_l[x] del self._levels_l[x] self._objectMan.dumpObjects(level.terminate()) for x in range(len(self._levelsWaitingObj_l) - 1, -1, -1): del self._levels_l[x] def deleteAnObject(self, levelName_s: str, objectName_s: str) -> bool: level = self.findLevelByName(levelName_s) if level is None: return False else: objTempName_s = level.deleteAnObject(objectName_s) if objTempName_s is not None: self._objectMan.dumpObjects([objTempName_s]) self.console.appendLogs( "An onject '{}' in level '{}' has been deleted.".format( objectName_s, levelName_s)) else: return False def getLevelWithNameInLevelsList(self, levelName_s: str) -> Optional[Level]: for level in self._levels_l: if level.getName() == levelName_s: return level else: return None def getLevelWithNameInLevelWaitingObjList( self, levelName_s: str) -> Optional[Level]: for level in self._levelsWaitingObj_l: if level.getName() == levelName_s: return level else: return None @staticmethod def __findLevelDir(levelName_s: str) -> str: for x_s in os.listdir(".\\assets\\levels\\"): if levelName_s == x_s: return ".\\assets\\levels\\" + x_s else: raise FileNotFoundError(levelName_s) def __popFromLevelLoader(self) -> None: if self._watingForLevel_i: try: result = self._fromLevelLoaderQueue.get_nowait() except Empty: return else: self._watingForLevel_i -= 1 if isinstance(result, tuple): # Failed to load a level. if result[0] == -1: # File does not exist. print("(Error) File not found:", result[1]) elif isinstance(result, Level): self._levelsWaitingObj_l.append(result) self._levels_l.append(result) text_s = "Level loaded: '{}'".format(result.getName()) print(text_s) self.console.appendLogs(text_s) else: raise ValueError( "Recived wrong data type from LevelLoader: {}".format( type(result))) def __fillLevelWithObjects(self) -> None: for x in range(len(self._levelsWaitingObj_l) - 1, -1, -1): level = self._levelsWaitingObj_l[x] for y in range(len(level.objectBlueprints_l) - 1, -1, -1): objBprint = level.objectBlueprints_l[y] if isinstance(objBprint, bp.ObjectDefineBlueprint): self._objectMan.giveObjectDefineBlueprint(objBprint) level.objectObjInitInfo_l.append( ObjectInitInfo(objBprint.name_s, objBprint.name_s, level, objBprint.static_b, objBprint.initPos_t, objBprint.colGroupTargets_l, [])) del level.objectBlueprints_l[y] elif isinstance(objBprint, bp.ObjectUseBlueprint): level.objectObjInitInfo_l.append( ObjectInitInfo(objBprint.name_s, objBprint.templateName_s, level, objBprint.static_b, objBprint.initPos_t, objBprint.colGroupTargets_l, [])) del level.objectBlueprints_l[y] elif isinstance(objBprint, bp.ObjectObjStaticBlueprint): self._objectMan.giveObjectObjStaticBlueprint(objBprint) level.objectObjInitInfo_l.append( ObjectInitInfo(objBprint.name_s, objBprint.objFileName_s, level, objBprint.static_b, objBprint.initPos_t, objBprint.colGroupTargets_l, objBprint.colliders_l)) del level.objectBlueprints_l[y] else: raise ValueError for y in range(len(level.objectObjInitInfo_l) - 1, -1, -1): objInitInfo = level.objectObjInitInfo_l[y] result = self._objectMan.requestObject(objInitInfo) if result is not None: del level.objectObjInitInfo_l[y] level.objects_l.append(result) if len(level.objectObjInitInfo_l) <= 0: del self._levelsWaitingObj_l[x]
nodes_next_second(nodes) UAV_AI.next_second(UAV, nodes, charge_mode, path_mode, 1.0, params) round_num += 1 left -= 1 def start_visualization(): global nodes, visualization_nodes_text visualization_nodes_text = [] for node in nodes: visualization_node_text = ax.text(node['x'], node['y'], '') visualization_nodes_text.append(visualization_node_text) ani = animation.FuncAnimation(fig, visualize_animate, interval=param_animation_frame_interval, blit=False) plt.show() object_manager_ = ObjectManager() round_num = 1 if using_last_system_state == True: UAV, nodes = object_manager_.read_objects_file('.tmp_state') else: UAV, nodes = object_manager_.create_objects(config) object_manager_.save_objects_file(UAV, nodes, '.tmp_state') path_x = [UAV['current_x']] path_y = [UAV['current_y']] # visualization # set up figure and animation fig = plt.figure(figsize=(12, 6)) gs = gridspec.GridSpec(1, 3, width_ratios=[9, 4, 1], wspace=0.5) ax = fig.add_subplot(gs[0], xlim=(-3, config.param_ground_width+3), ylim=(-3, config.param_ground_height+3))
def redo(self): (next_fp, next_modified) = self._redo_list.pop() self._undo_list.append((next_fp, next_modified)) new_object_manager = ObjectManager.from_dict(next_fp) self.set_object_manager(new_object_manager) self.emit("modified", next_modified)
class FPArea(gtk.DrawingArea): @classmethod def new(cls): self = cls() self.show() self.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.KEY_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK) self.connect("button-press-event", cls.click_event) self.connect("button-release-event", cls.release_event) self.connect("expose-event", cls.expose_event) self.connect("motion-notify-event", cls.motion_notify_event) self.connect("configure-event", cls.configure_event) self.connect("key-press-event", cls.key_press_event) self.connect("scroll-event", cls.scroll_event) # Where we last saw the mouse. self.x = 0 self.y = 0 # Offsets for converting between screen coordinates and logical # coordinates. self.scale_x = 100 self.scale_y = 100 # How far zoomed we are. Higher numbers mean more zoomed in. self.scale_factor = 1 self.pixmap = None # Whether we're currently in the middle of a drag. self.dragging = False self.object_manager = ObjectManager() self.active_object = None self.dragging_object = None self.selected_primitives = set() # Create the center point p = CenterPoint(self.object_manager, set()) self.object_manager.add_primitive(p) self.deselect_all() return self def scroll_event(self, event): # When the scroll wheel is used, zoom in or out. x, y = self.coord_map(event.x, event.y) print(x, y) if event.direction == gtk.gdk.SCROLL_UP: self.scale_factor *= 1.3 elif event.direction == gtk.gdk.SCROLL_DOWN: self.scale_factor /= 1.3 self.scale_x = event.x / self.scale_factor - x self.scale_y = event.y / self.scale_factor - y print(self.scale_factor, self.scale_x, self.scale_y) self.queue_draw() def recalculate(self): self.object_manager.update_points() def deselect_all(self): self.selected_primitives.clear() def delete(self, obj): for p in self.primitives: if obj in p.children(): # We're a child primitive which must only be deleted through # the parent. return to_remove = set([self.active_object]) while True: changed = False l = len(to_remove) new_to_remove = set() for c in to_remove: new_to_remove.update(c.children()) to_remove.update(new_to_remove) changed = changed or l != len(to_remove) for p in self.primitives: if p in to_remove: continue if to_remove.intersection(p.dependencies()): to_remove.update([p]) changed = True if not changed: break for p in to_remove: self.primitives.remove(p) # TODO: these should be sets. if p in self.draw_primitives: self.draw_primitives.remove(p) def key_press_event(self, event): # TODO: refactor this so it's not some monolithic function # with what's effectively a huge case statement. It's not too # terrible right now, but as more gets added it will quickly # become worse. primitive_table = { 'h': Horizontal, 'v': Vertical, 'd': HorizDistance, } keyname = gtk.gdk.keyval_name(event.keyval) print(keyname) if keyname == 'a': p = Pad(self.object_manager, self.x, self.y, 100, 50) self.object_manager.add_primitive(p) self.recalculate() elif keyname == 'p': p = PadArray(self.object_manager, self.x, self.y) self.object_manager.add_primitive(p) self.recalculate() elif keyname == 'Delete': print(self.active_object) if self.active_object is not None: self.delete(self.active_object) self.recalculate() elif keyname == 'dd': if len(self.selected_primitives) == 2: l = list(self.selected_primitives) p = HorizDistance(self.object_manager, l[0], l[1], 100, 30) self.object_manager.add_primitive(p) self.selected_primitives.clear() else: print("Select two points.") self.recalculate() elif keyname == 'space': if self.active_object is not None: if self.active_object in self.selected_primitives: self.selected_primitives.remove(self.active_object) self.active_object.deselect() else: self.selected_primitives.add(self.active_object) self.active_object.select() elif keyname == 'q': exit() else: cls = primitive_table.get(keyname) if cls: if cls.can_create(self.selected_primitives): p = cls(self.object_manager, self.selected_primitives) self.object_manager.add_primitive(p) self.deselect_all() else: print("Cannot create constraint.") self.recalculate() self.update_closest() self.queue_draw() def configure_event(self, event): x, y, width, height = self.get_allocation() self.pixmap = gtk.gdk.Pixmap(self.window, width, height) self.pixmap.draw_rectangle(self.get_style().white_gc, True, 0, 0, width, height) return True def expose_event(self, event): x, y, width, height = event.area self.window.draw_drawable(self.get_style().fg_gc[gtk.STATE_NORMAL], self.pixmap, x, y, x, y, width, height) cr = self.window.cairo_create() # cr.rectangle(event.area.x, event.area.y, # event.area.width, event.area.height) # cr.clip() self.draw(cr) return False def coord_map(self, x, y): ''' Given pixel coordinates on the screen, return the corresponding logical coordinates. ''' return (x / self.scale_factor - self.scale_x, y / self.scale_factor - self.scale_y) def update_closest(self): (p, dist) = self.object_manager.closest(self.x, self.y) if dist < 100: if self.active_object is not None and p is not None: self.active_object.deactivate() self.active_object = p if p is not None: p.activate() else: if self.active_object is not None: self.active_object.deactivate() self.active_object = None def draw(self, cr): cr.save() cr.scale(self.scale_factor, self.scale_factor) cr.translate(self.scale_x, self.scale_y) # cr.set_source_rgb(1, 1, 0) # cr.arc(self.x, self.y, 2, 0, 6.2) # cr.fill() for primitive in self.object_manager.draw_primitives: cr.save() primitive.draw(cr) cr.restore() if self.object_manager.point_coords: self.update_closest() return # cr.restore() # cr.move_to(10, 10) # cr.show_text("(%s, %s)" % (x, y)) # cr.stroke() def draw_pixmap(self, width, height): rect = (int(self.x - 5), int(self.y - 5), 10, 10) cr = self.pixmap.cairo_create() cr.set_source_rgb(0.5, 0.5, 0.5) cr.rectangle(rect[0], rect[1], 10, 10) cr.fill() self.queue_draw() def motion_notify_event(self, event): if event.is_hint: x, y, state = event.window.get_pointer() else: x = event.x y = event.y # state = event.state orig_x, orig_y = self.x, self.y self.x, self.y = self.coord_map(x, y) if self.dragging: self.scale_x += (self.x - orig_x) self.scale_y += (self.y - orig_y) self.x, self.y = self.coord_map(x, y) if self.dragging_object is not None: self.dragging_object.drag(self.x - orig_x, self.y - orig_y) self.queue_draw() return True def click_event(self, event): x, y = self.coord_map(event.x, event.y) print(event.button) print("Click %s %s" % (x, y)) if event.button == 1: if self.active_object is not None: print("Start drag") self.dragging_object = self.active_object self.dragging_object.drag(0, 0) self.recalculate() else: self.dragging_object = None self.queue_draw() elif event.button == 2: self.dragging = True return True def release_event(self, event): print(event) if event.button == 1: print("Relase drag") self.dragging_object = None elif event.button == 2: self.dragging = False
if node['power'] <= 0: return False return True def is_valid_UAV(UAV): if UAV['power'] <= 0: return False else: return True def nodes_next_second(nodes): for node in nodes: node['power'] -= node['rate'] # create object manager to create system object_manager_ = ObjectManager() # write the first line of the result res_file = open(param_res_file_name, 'w') if is_single_flight: res_file.write('network_type,UAV_mode,round_number\n') else: res_file.write('network_type,UAV_mode,flight_number\n') # create the file for experiment_time in range(param_experiment_time): print experiment_time for num in param_number_nodes: for size in param_ground_size: for localization_time in param_UAV_localization_time:
class FPArea(gtk.DrawingArea): @classmethod def new(cls): self = cls() self.show() self.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.KEY_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK) self.connect("button-press-event", cls.click_event) self.connect("button-release-event", cls.release_event) self.connect("expose-event", cls.expose_event) self.connect("motion-notify-event", cls.motion_notify_event) self.connect("configure-event", cls.configure_event) self.connect("key-press-event", cls.key_press_event) self.connect("scroll-event", cls.scroll_event) # Where we last saw the mouse. self.x = 0 self.y = 0 # Offsets for converting between screen coordinates and logical # coordinates. self.scale_x = 100 self.scale_y = 100 # How far zoomed we are. Higher numbers mean more zoomed in. self.scale_factor = 1 self.pixmap = None # Whether we're currently in the middle of a drag. self.dragging = False self.object_manager = ObjectManager() self.active_object = None self.dragging_object = None self.selected_primitives = set() # Create the center point p = CenterPoint(self.object_manager, set()) self.object_manager.add_primitive(p) self.deselect_all() return self def scroll_event(self, event): # When the scroll wheel is used, zoom in or out. x, y = self.coord_map(event.x, event.y) print(x, y) if event.direction == gtk.gdk.SCROLL_UP: self.scale_factor *= 1.3 elif event.direction == gtk.gdk.SCROLL_DOWN: self.scale_factor /= 1.3 self.scale_x = event.x / self.scale_factor - x self.scale_y = event.y / self.scale_factor - y print(self.scale_factor, self.scale_x, self.scale_y) self.queue_draw() def recalculate(self): self.object_manager.update_points() def deselect_all(self): self.selected_primitives.clear() def delete(self, obj): for p in self.primitives: if obj in p.children(): # We're a child primitive which must only be deleted through # the parent. return to_remove = set([self.active_object]) while True: changed = False l = len(to_remove) new_to_remove = set() for c in to_remove: new_to_remove.update(c.children()) to_remove.update(new_to_remove) changed = changed or l != len(to_remove) for p in self.primitives: if p in to_remove: continue if to_remove.intersection(p.dependencies()): to_remove.update([p]) changed = True if not changed: break for p in to_remove: self.primitives.remove(p) # TODO: these should be sets. if p in self.draw_primitives: self.draw_primitives.remove(p) def key_press_event(self, event): # TODO: refactor this so it's not some monolithic function # with what's effectively a huge case statement. It's not too # terrible right now, but as more gets added it will quickly # become worse. primitive_table = { 'h': Horizontal, 'v': Vertical, 'd': HorizDistance, } keyname = gtk.gdk.keyval_name(event.keyval) print(keyname) if keyname == 'a': p = Pad(self.object_manager, self.x, self.y, 100, 50) self.object_manager.add_primitive(p) self.recalculate() elif keyname == 'p': p = PadArray(self.object_manager, self.x, self.y) self.object_manager.add_primitive(p) self.recalculate() elif keyname == 'Delete': print(self.active_object) if self.active_object is not None: self.delete(self.active_object) self.recalculate() elif keyname == 'dd': if len(self.selected_primitives) == 2: l = list(self.selected_primitives) p = HorizDistance(self.object_manager, l[0], l[1], 100, 30) self.object_manager.add_primitive(p) self.selected_primitives.clear() else: print("Select two points.") self.recalculate() elif keyname == 'space': if self.active_object is not None: if self.active_object in self.selected_primitives: self.selected_primitives.remove(self.active_object) self.active_object.deselect() else: self.selected_primitives.add(self.active_object) self.active_object.select() elif keyname == 'q': exit() else: cls = primitive_table.get(keyname) if cls: if cls.can_create(self.selected_primitives): p = cls(self.object_manager, self.selected_primitives) self.object_manager.add_primitive(p) self.deselect_all() else: print("Cannot create constraint.") self.recalculate() self.update_closest() self.queue_draw() def configure_event(self, event): x, y, width, height = self.get_allocation() self.pixmap = gtk.gdk.Pixmap(self.window, width, height) self.pixmap.draw_rectangle(self.get_style().white_gc, True, 0, 0, width, height) return True def expose_event(self, event): x, y, width, height = event.area self.window.draw_drawable(self.get_style().fg_gc[gtk.STATE_NORMAL], self.pixmap, x, y, x, y, width, height) cr = self.window.cairo_create() # cr.rectangle(event.area.x, event.area.y, # event.area.width, event.area.height) # cr.clip() self.draw(cr) return False def coord_map(self, x, y): ''' Given pixel coordinates on the screen, return the corresponding logical coordinates. ''' return (x / self.scale_factor - self.scale_x, y / self.scale_factor - self.scale_y) def update_closest(self): (p, dist) = self.object_manager.closest(self.x, self.y) if dist < 100: if self.active_object is not None and p is not None: self.active_object.deactivate() self.active_object = p if p is not None: p.activate() else: if self.active_object is not None: self.active_object.deactivate() self.active_object = None def draw(self, cr): cr.save() cr.scale(self.scale_factor, self.scale_factor) cr.translate(self.scale_x, self.scale_y) # cr.set_source_rgb(1, 1, 0) # cr.arc(self.x, self.y, 2, 0, 6.2) # cr.fill() for primitive in self.object_manager.draw_primitives: cr.save() primitive.draw(cr) cr.restore() if self.object_manager.point_coords: self.update_closest() return # cr.restore() # cr.move_to(10, 10) # cr.show_text("(%s, %s)" % (x, y)) # cr.stroke() def draw_pixmap(self, width, height): rect = (int(self.x-5), int(self.y-5), 10, 10) cr = self.pixmap.cairo_create() cr.set_source_rgb(0.5, 0.5, 0.5) cr.rectangle(rect[0], rect[1], 10, 10) cr.fill() self.queue_draw() def motion_notify_event(self, event): if event.is_hint: x, y, state = event.window.get_pointer() else: x = event.x y = event.y # state = event.state orig_x, orig_y = self.x, self.y self.x, self.y = self.coord_map(x, y) if self.dragging: self.scale_x += (self.x - orig_x) self.scale_y += (self.y - orig_y) self.x, self.y = self.coord_map(x, y) if self.dragging_object is not None: self.dragging_object.drag(self.x - orig_x, self.y - orig_y) self.queue_draw() return True def click_event(self, event): x, y = self.coord_map(event.x, event.y) print(event.button) print("Click %s %s" % (x, y)) if event.button == 1: if self.active_object is not None: print("Start drag") self.dragging_object = self.active_object self.dragging_object.drag(0, 0) self.recalculate() else: self.dragging_object = None self.queue_draw() elif event.button == 2: self.dragging = True return True def release_event(self, event): print(event) if event.button == 1: print("Relase drag") self.dragging_object = None elif event.button == 2: self.dragging = False
print( "Usage: python module_generate_obj_videos.py src_dir_path trackerpath") raise Exception("GenerateObjVideos: main --> Input arguments != 3.") src_dir_path = sys.argv[1] tracker_path = sys.argv[2] tmp_dir = tracker_path[: -11] # remove the file from tracker_path to get the tmp dir # Load the tracker file = open(tracker_path, 'rb') tracker = pickle.load(file) file.close() # Add all the objects to the object manager obj_manager = ObjectManager() for f in range(0, len(tracker.getFrames())): frame = tracker.getFrame(f) obj_manager.add_frame(frame.getObjects(), f) # Compute the maximum bbox for each of the objects obj_manager.compute_obj_max_bboxes() # Get the frames for each of the objects and write the videos max_bboxes = obj_manager.getMaxBboxObjects() fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') for f in range(0, len(tracker.getFrames())): frame = tracker.getFrame(f) image = cv2.imread(src_dir_path + "anim_{id}_4k.png".format(id=frame.getKey())) frame_heigth, frame_width, _ = image.shape
from pygame import mixer import player import screen from object_manager import ObjectManager from enemy import EnemyManager from help import getch, log player = player.Player(x=2, y=4, px=2, py=2, health=5, inventory=[]) move_commands = ['d', 'a', 's', 'w'] attack_commands = ['j', 'k', 'l', 'i', 'm'] map = screen.MapController() enemy_manager = EnemyManager() object_manager = ObjectManager() mixer.init() mixer.Sound("sounds/noodle.wav").play(-1) playing = True # set console size command = 'mode con: cols={} lines={}'.format(map.columns, map.rows+2) os.system(command) # player ui, world ui pui = "" wui = "" while playing: # updates the map with player pos, all room objects # Enemy positions and the player and world UIs