def run(self): """ 'Selects' objects and sets according values for defined attributes/custom properties.""" instances = self.config.get_list("instances", []) for instance in instances: # separating defined part with the selector from ambiguous part with attribute names and their values to set set_params = {} sel_objs = {} for key in instance.keys(): # if its not a selector -> to the set parameters dict if key != 'selector': set_params[key] = instance[key] else: sel_objs[key] = instance[key] # create Config objects params_conf = Config(set_params) sel_conf = Config(sel_objs) # invoke a Getter, get a list of objects to manipulate objects = sel_conf.get_list("selector") for key in params_conf.data.keys(): # get raw value from the set parameters config object result = params_conf.get_raw_value(key) for obj in objects: # if an attribute with such name exists for this object if hasattr(obj, key): # set the value setattr(obj, key, result) # if not, then treat it as a custom property. Values will be overwritten for existing custom # property, but if the name is new then new custom property will be created else: obj[key] = result
def run(self): """ Sets according values of defined attributes or applies custom functions to the selected materials. 1. Select materials. 2. For each parameter to modify, set it's value to all selected objects. """ set_params = {} sel_objs = {} for key in self.config.data.keys(): # if its not a selector -> to the set parameters dict if key != 'selector': set_params[key] = self.config.data[key] else: sel_objs[key] = self.config.data[key] # create Config objects params_conf = Config(set_params) sel_conf = Config(sel_objs) # invoke a Getter, get a list of entities to manipulate materials = sel_conf.get_list("selector") op_mode = self.config.get_string("mode", "once_for_each") if op_mode == "once_for_all": # get values to set if they are to be set/sampled once for all selected materials params = self._get_the_set_params(params_conf) for material in materials: if not material.use_nodes: raise Exception("This material does not use nodes -> not supported here.") if op_mode == "once_for_each": # get values to set if they are to be set/sampled anew for each selected entity params = self._get_the_set_params(params_conf) for key, value in params.items(): # used so we don't modify original key when having more than one material key_copy = key requested_cf = False if key.startswith('cf_'): requested_cf = True key_copy = key[3:] # if an attribute with such name exists for this entity if key_copy == "color_link_to_displacement" and requested_cf: MaterialManipulator._link_color_to_displacement_for_mat(material, value) elif key_copy == "change_to_vertex_color" and requested_cf: MaterialManipulator._map_vertex_color(material, value) elif key_copy == "textures" and requested_cf: loaded_textures = self._load_textures(value) self._set_textures(loaded_textures, material) elif key_copy == "switch_to_emission_shader" and requested_cf: self._switch_to_emission_shader(material, value) elif "set_" in key_copy and requested_cf: # sets the value of the principled shader self._set_principled_shader_value(material, key_copy[len("set_"):], value) elif hasattr(material, key_copy): # set the value setattr(material, key_copy, value)
def _get_the_set_params(self, params_conf): """ Extracts actual values to set from a Config object. :param params_conf: Object with all user-defined data. Type: Config. :return: Parameters to set as {name of the parameter: it's value} pairs. Type: dict. """ params = {} for key in params_conf.data.keys(): if key == "cf_add_modifier": modifier_config = Config(params_conf.get_raw_dict(key)) # instruction about unpacking the data: key, corresponding Config method to extract the value, # it's default value and a postproc function instructions = {"name": (Config.get_string, None, str.upper), "thickness": (Config.get_float, None, None)} # unpack result = self._unpack_params(modifier_config, instructions) elif key == "cf_set_shading": result = {"shading_mode": params_conf.get_string("cf_set_shading"), "angle_value": params_conf.get_float("cf_shading_auto_smooth_angle_in_deg", 30)} elif key == "cf_add_displace_modifier_with_texture": displace_config = Config(params_conf.get_raw_dict(key)) # instruction about unpacking the data: key, corresponding Config method to extract the value, # it's default value and a postproc function instructions = {"texture": (Config.get_raw_value, [], None), "mid_level": (Config.get_float, 0.5, None), "subdiv_level": (Config.get_int, 2, None), "strength": (Config.get_float, 0.1, None), "min_vertices_for_subdiv": (Config.get_int, 10000, None)} # unpack result = self._unpack_params(displace_config, instructions) elif key == "cf_add_uv_mapping": uv_config = Config(params_conf.get_raw_dict(key)) # instruction about unpacking the data: key, corresponding Config method to extract the value, # it's default value and a postproc function instructions = {"projection": (Config.get_string, None, str.lower), "forced_recalc_of_uv_maps": (Config.get_bool, False, None)} # unpack result = self._unpack_params(uv_config, instructions) elif key == "cf_randomize_materials": rand_config = Config(params_conf.get_raw_dict(key)) # instruction about unpacking the data: key, corresponding Config method to extract the value, # it's default value and a postproc function instructions = {"randomization_level": (Config.get_float, 0.2, None), "add_to_objects_without_material": (Config.get_bool, False, None), "materials_to_replace_with": (Config.get_list, BlenderUtility.get_all_materials(), None), "obj_materials_cond_to_be_replaced": (Config.get_raw_dict, {}, None)} result = self._unpack_params(rand_config, instructions) else: result = params_conf.get_raw_value(key) params.update({key: result}) return params
def run(self): """ Loads rocks and constructs ground plane. """ rocks_settings = self.config.get_list("rocks", []) for subsec_num, subsec_settings in enumerate(rocks_settings): subsec_config = Config(subsec_settings) subsec_objects = self._load_rocks(subsec_num, subsec_config) self._set_rocks_properties(subsec_objects, subsec_config) ground_settings = self.config.get_raw_dict("ground", {}) if ground_settings: ground_config = Config(ground_settings) self._load_shader(ground_config) loaded_images = self._load_images(ground_config) self._construct_ground_plane(loaded_images, ground_config)
def run(self): """ Returns the result of processing of the list of values. """ transform_by = self.config.get_string("transform_by") elements = self.config.get_list("elements") raw_result = [] for element in elements: element_conf = Config({"element": element}) if isinstance(element, list): raw_result.append(element_conf.get_vector3d("element")) else: raw_result.append(element_conf.get_raw_value("element")) if len(raw_result) > 0: if self._check_compatibility(raw_result): if transform_by == "sum": ref_result = self._sum(raw_result) elif transform_by == "avg": ref_result = self._avg(raw_result) else: raise RuntimeError("Unknown 'transform_by' operation: " + transform_by) else: raise RuntimeError( "Provider output types don't match. All must either int, float, or mathutils.Vector." ) else: raise RuntimeError( "List of resulting values of `elements` is empty. Please, check Provider configuration." ) return ref_result
def build_provider(name, parameters): """ Builds up providers like sampler or getter. It first builds the config and then constructs the required provider. :param name: The name of the provider class. :param parameters: A dict containing the parameters that should be used. :return: The constructed provider. """ module_class = None for suffix in ["Module", ""]: try: # Import class from src.utility module_class = getattr(importlib.import_module("src.provider." + name + suffix), name.split(".")[-1] + suffix) break except ModuleNotFoundError: # Try next suffix continue # Throw an error if no module/class with the specified name + any suffix has been found if module_class is None: raise Exception("The module src.provider." + name + " was not found!") # Build configuration config = Config(parameters) # Construct provider return module_class(config)
def sample_and_validate_cam_pose(self, cam, cam_ob, config): """ Samples a new camera pose, sets the parameters of the given camera object accordingly and validates it. :param cam: The camera which contains only camera specific attributes. :param cam_ob: The object linked to the camera which determines general properties like location/orientation :param config: The config object describing how to sample :return: True, if the sampled pose was valid """ # Sample used floor obj floor_obj = random.choice(self.used_floors) # Sample/set intrinsics self._set_cam_intrinsics(cam, Config(self.config.get_raw_dict("intrinsics", {}))) # Sample camera extrinsics (we do not set them yet for performance reasons) cam2world_matrix = self._cam2world_matrix_from_cam_extrinsics(config) # Make sure the sampled location is inside the room => overwrite x and y and add offset to z bounding_box = get_bounds(floor_obj) min_corner = np.min(bounding_box, axis=0) max_corner = np.max(bounding_box, axis=0) cam2world_matrix.translation[0] = random.uniform(min_corner[0], max_corner[0]) cam2world_matrix.translation[1] = random.uniform(min_corner[1], max_corner[1]) cam2world_matrix.translation[2] += floor_obj.location[2] # Check if sampled pose is valid if self._is_pose_valid(floor_obj, cam, cam_ob, cam2world_matrix): # Set camera extrinsics as the pose is valid CameraUtility.add_camera_pose(cam2world_matrix) return True else: return False
def sample_and_validate_cam_pose(self, cam, cam_ob, config): """ Samples a new camera pose, sets the parameters of the given camera object accordingly and validates it. :param cam: The camera which contains only camera specific attributes. :param cam_ob: The object linked to the camera which determines general properties like location/orientation :param config: The config object describing how to sample :return: True, if the sampled pose was valid """ # Sample/set intrinsics self._set_cam_intrinsics( cam, Config(self.config.get_raw_dict("intrinsics", {}))) # Sample camera extrinsics (we do not set them yet for performance reasons) cam2world_matrix = self._cam2world_matrix_from_cam_extrinsics(config) # Make sure the sampled location is inside the room => overwrite x and y and add offset to z cam2world_matrix.translation[0] = random.uniform( self.bounding_box["min"][0], self.bounding_box["max"][0]) cam2world_matrix.translation[1] = random.uniform( self.bounding_box["min"][1], self.bounding_box["max"][1]) cam2world_matrix.translation[2] += self.floor_height_values[ random.randrange(0, len(self.floor_height_values))] # Check if sampled pose is valid if self._is_pose_valid(cam, cam_ob, cam2world_matrix): # Set camera extrinsics as the pose is valid CameraUtility.add_camera_pose(cam2world_matrix) return True else: return False
def build_provider_based_on_config(config): """ Builds up the provider using the parameters described in the given config. The given config should follow the following scheme: .. code-block:: yaml { "provider": "<name of provider class>" "parameters": { <provider parameters> } } :param config: A Configuration object or a dict containing the configuration data. :return: The constructed provider. """ if isinstance(config, dict): config = Config(config) parameters = {} for key in config.data.keys(): if key != 'provider': parameters[key] = config.data[key] if not config.has_param('provider'): raise Exception("Each provider needs a provider label, this one does not contain one: {}".format(config.data)) return Utility.build_provider(config.get_string("provider"), parameters)
def run(self): """ Loads rocks.""" rocks_settings = self.config.get_list("batches", []) for subsec_num, subsec_settings in enumerate(rocks_settings): subsec_config = Config(subsec_settings) subsec_objects = RockEssentialsRockLoader.load_rocks( path=subsec_config.get_string("path"), subsec_num=subsec_num, objects=subsec_config.get_list("objects", []), sample_objects=subsec_config.get_bool("sample_objects", False), amount=subsec_config.get_int("amount") if subsec_config.has_param("amount") else None ) RockEssentialsRockLoader.set_rocks_properties( objects=subsec_objects, physics=subsec_config.get_bool("physics", False), render_levels=subsec_config.get_int("render_levels", 3), high_detail_mode=subsec_config.get_bool("high_detail_mode", False), scale=subsec_config.get_vector3d("scale", [1, 1, 1]), reflection_amount=subsec_config.get_float("reflection_amount") if subsec_config.has_param("reflection_amount") else None, reflection_roughness=subsec_config.get_float("reflection_roughness") if subsec_config.has_param("reflection_roughness") else None, hsv=subsec_config.get_list("HSV") if subsec_config.has_param("HSV") else None )
def _get_the_set_params(self, params_conf): """ Extracts actual values to set from a Config object. :param params_conf: Object with all user-defined data. Type: Config. :return: Parameters to set as {name of the parameter: it's value} pairs. Type: dict. """ params = {} for key in params_conf.data.keys(): result = None if key == "color_link_to_displacement": result = params_conf.get_float(key) elif key == "change_to_vertex_color": result = params_conf.get_string(key) elif key == "textures": result = {} paths_conf = Config(params_conf.get_raw_dict(key)) for text_key in paths_conf.data.keys(): text_path = paths_conf.get_string(text_key) result.update({text_key: text_path}) else: result = params_conf.get_raw_value(key) params.update({key: result}) return params
def run(self): """ Extracts floors in the following steps: 1. Searchs for the specified object. 2. Splits the surfaces which point upwards at a specified level away. """ mesh_objects = [] for obj in self.config.get_list("selector"): if obj.type != "MESH": warnings.warn( "The object: {} is not a mesh but was selected in the FloorExtractor!" .format(obj.name)) continue mesh_objects.append(MeshObject(obj)) floors = FloorExtractor.extract( mesh_objects=mesh_objects, compare_angle_degrees=radians( self.config.get_float('compare_angle_degrees', 7.5)), compare_height=self.config.get_float('compare_height', 0.15), new_name_for_object=self.config.get_string("name_for_split_obj", "Floor"), should_skip_if_object_is_already_there=self.config.get_bool( "should_skip_if_object_is_already_there", False)) add_properties = self.config.get_raw_dict("add_properties", {}) if add_properties: config = Config({"add_properties": add_properties}) loader_interface = LoaderInterface(config) loader_interface._set_properties(floors)
def initialize_modules(module_configs): """ Initializes the modules described in the given configuration. Example for module_configs: .. code-block:: yaml [{ "module": "base.ModuleA", "config": {...} }, ...] If you want to execute a certain module several times, add the `amount_of_repetions` on the same level as the module name: .. code-block:: yaml [{ "module": "base.ModuleA", "config": {...}, "amount_of_repetitions": 3 }, ...] Here the name contains the path to the module class, starting from inside the src directory. Be aware that all attributes stored in the GlobalStorage are also accessible here, even though they are not copied into the new config. :param module_configs: A list of dicts, each one describing one module. :return: a list of initialized modules """ modules = [] for module_config in module_configs: # If only the module name is given (short notation) if isinstance(module_config, str): module_config = {"module": module_config} # Initialize config with empty config config = {} # Check if there is a module specific config if "config" in module_config: # Overwrite with module specific config Utility.merge_dicts(module_config["config"], config) # Check if the module has a repetition counter amount_of_repetitions = 1 if "amount_of_repetitions" in module_config: amount_of_repetitions = module_config["amount_of_repetitions"] with Utility.BlockStopWatch("Initializing module " + module_config["module"]): for i in range(amount_of_repetitions): # Import file and extract class module_class = getattr(importlib.import_module("src." + module_config["module"]), module_config["module"].split(".")[-1]) # Create module modules.append(module_class(Config(config))) return modules
def run(self): # Set intrinsics self._set_cam_intrinsics(bpy.context.scene.camera.data, Config(self.config.get_raw_dict("intrinsics", {}))) self.cam_pose_collection.add_items_from_dicts(self.config.get_list("cam_poses", [])) self.cam_pose_collection.add_items_from_file(self.config.get_string("path", ""), self.config.get_string("file_format", ""), self.number_of_arguments_per_parameter)
def run(self): """ Loads rocks.""" rocks_settings = self.config.get_list("batches", []) for subsec_num, subsec_settings in enumerate(rocks_settings): subsec_config = Config(subsec_settings) subsec_objects = self._load_rocks(subsec_num, subsec_config) self._set_rocks_properties(subsec_objects, subsec_config)
def _get_the_set_params(self, params_conf: Config) -> dict: """ Extracts actual values to set from a Config object. :param params_conf: Object with all user-defined data. :return: Parameters to set as {name of the parameter: it's value} pairs. """ params = {} for key in params_conf.data.keys(): result = None if key == "cf_color_link_to_displacement": result = params_conf.get_float(key) elif key == "cf_change_to_vertex_color": result = params_conf.get_string(key) elif key == "cf_textures": result = {} paths_conf = Config(params_conf.get_raw_dict(key)) for text_key in paths_conf.data.keys(): text_path = paths_conf.get_string(text_key) result.update({text_key: text_path}) elif key == "cf_switch_to_emission_shader": result = {} emission_conf = Config(params_conf.get_raw_dict(key)) for emission_key in emission_conf.data.keys(): if emission_key == "color": attr_val = emission_conf.get_list( "color", [1, 1, 1, 1]) elif emission_key == "strength": attr_val = emission_conf.get_float("strength", 1.0) else: attr_val = emission_conf.get_raw_value(emission_key) result.update({emission_key: attr_val}) elif key == "cf_infuse_texture": result = Config(params_conf.get_raw_dict(key)) elif key == "cf_infuse_material": result = Config(params_conf.get_raw_dict(key)) elif key == "cf_add_dust": result = params_conf.get_raw_dict(key) elif "cf_set_" in key or "cf_add_" in key: result = params_conf.get_raw_value(key) else: result = params_conf.get_raw_value(key) params.update({key: result}) return params
def run(self): """ 'Selects' entities and sets according values for defined attributes/custom properties.""" # separating defined part with the selector from ambiguous part with attribute names and their values to set set_params = {} sel_objs = {} for key in self.config.data.keys(): # if its not a selector -> to the set parameters dict if key != 'selector': set_params[key] = self.config.data[key] else: sel_objs[key] = self.config.data[key] # create Config objects params_conf = Config(set_params) sel_conf = Config(sel_objs) # invoke a Getter, get a list of entities to manipulate entities = sel_conf.get_list("selector") op_mode = self.config.get_string("mode", "once_for_each") for key in params_conf.data.keys(): # get raw value from the set parameters if it is to be sampled once for all selected entities if op_mode == "once_for_all": result = params_conf.get_raw_value(key) for entity in entities: if op_mode == "once_for_each": # get raw value from the set parameters if it is to be sampled anew for each selected entity result = params_conf.get_raw_value(key) # check if the key is a requested custom property requested_custom_property = False if key.startswith('cp_'): requested_custom_property = True key = key[3:] # if an attribute with such name exists for this entity if hasattr(entity, key) and not requested_custom_property: # set the value setattr(entity, key, result) # if not, then treat it as a custom property. Values will be overwritten for existing custom # property, but if the name is new then new custom property will be created else: entity[key] = result # update all entities matrices bpy.context.view_layer.update()
def __init__(self, config): Module.__init__(self, config) # setting up the GlobalStorage global_config = Config(self.config.get_raw_dict("global", {})) GlobalStorage.init_global(global_config) # call the init again to make sure all values from the global config where read correctly, too self._default_init()
def run(self): """ Constructs ground plane. """ tiles = self.config.get_list("tiles", []) for tile in tiles: if tile: ground_config = Config(tile) self._load_shader(ground_config) self._construct_ground_plane(ground_config)
def initialize_modules(module_configs, global_config): """ Initializes the modules described in the given configuration. Example for module_configs: [{ "module": "base.ModuleA", "config": {...} }, ...] Here the name contains the path to the module class, starting from inside the src directory. Example for global_config: {"base": { param: 42 }} In this way all modules with prefix "base" will inherit "param" into their configuration. Local config always overwrites global. Parameters specified under "all" in the global config are inherited by all modules. :param module_configs: A list of dicts, each one describing one module. :param global_config: A dict containing the global configuration. :return: """ modules = [] all_base_config = global_config[ "all"] if "all" in global_config else {} for module_config in module_configs: # If only the module name is given (short notation) if isinstance(module_config, str): module_config = {"module": module_config} # Merge global and local config (local overwrites global) model_type = module_config["module"].split(".")[0] base_config = global_config[ model_type] if model_type in global_config else {} # Initialize config with all_base_config config = deepcopy(all_base_config) # Overwrite with module type base config Utility.merge_dicts(base_config, config) # Check if there is a module specific config if "config" in module_config: # Overwrite with module specific config Utility.merge_dicts(module_config["config"], config) with Utility.BlockStopWatch("Initializing module " + module_config["module"]): # Import file and extract class module_class = getattr( importlib.import_module("src." + module_config["module"]), module_config["module"].split(".")[-1]) # Create module modules.append(module_class(Config(config))) return modules
def run(self): own_config = Config({"selector": {"provider": "getter.Entity", "conditions": { "cp_is_scene_net_obj": True }}}) # get all objects which have the custom property is_scene_net_obj: True objects = own_config.get_list("selector") if not objects: raise Exception("No objects have been loaded which have the custom property is_scene_net_obj!") self.add_emission_to_materials(objects)
def run(self): set_params = {} sel_objs = {} for key in self.config.data.keys(): # if its not a selector -> to the set parameters dict if key != 'selector': set_params[key] = self.config.data[key] else: sel_objs[key] = self.config.data[key] # create Config objects params_conf = Config(set_params) sel_conf = Config(sel_objs) # invoke a Getter, get a list of entities to manipulate materials = sel_conf.get_list("selector") op_mode = self.config.get_string("mode", "once_for_each") if op_mode == "once_for_all": # get values to set if they are to be set/sampled once for all selected materials params = self._get_the_set_params(params_conf) for material in materials: if not material.use_nodes: raise Exception( "This material does not use nodes -> not supported here.") if op_mode == "once_for_each": # get values to set if they are to be set/sampled anew for each selected entity params = self._get_the_set_params(params_conf) for key, value in params.iteritems(): # if an attribute with such name exists for this entity if key == "color_link_to_displacement": MaterialManipulator._link_color_to_displacement_for_mat( material, value) elif key == "change_to_vertex_color": MaterialManipulator._map_vertex_color(material, value) elif key == "textures": loaded_textures = self._load_textures(value) self._set_textures(loaded_textures, material) elif hasattr(material, key): # set the value setattr(material, key, value)
def _get_random_texture(self, textures): """ Chooses a random texture data from the provided list. :param textures: Texture data. Type: list. :return: Selected texture data. Type: Config. """ selected_dict = choice(textures) selected_texture = Config(selected_dict) return selected_texture
def _get_random_texture(self, textures): """ Chooses a random texture data from the provided list. :param textures: List of dicts. Each dict is describing a texture data (path to images, images, etc.). :return: A config object of the selected texture dict. """ selected_dict = choice(textures) selected_texture = Config(selected_dict) return selected_texture
def _get_the_set_params(self, params_conf): """ Extracts actual values to set from a Config object. :param params_conf: Object with all user-defined data. Type: Config. :return: Parameters to set as {name of the parameter: it's value} pairs. Type: dict. """ params = {} for key in params_conf.data.keys(): if key == "cf_add_modifier": modifier_config = Config(params_conf.get_raw_dict(key)) # instruction about unpacking the data: key, corresponding Config method to extract the value, # it's default value and a postproc function instructions = {"name": (Config.get_string, None, str.upper), "thickness": (Config.get_float, None, None)} # unpack result = self._unpack_params(modifier_config, instructions) elif key == "cf_set_shading": result = params_conf.get_string("cf_set_shading") elif key == "cf_add_displace_modifier_with_texture": displace_config = Config(params_conf.get_raw_dict(key)) # instruction about unpacking the data: key, corresponding Config method to extract the value, # it's default value and a postproc function instructions = {"texture": (Config.get_raw_value, [], None), "mid_level": (Config.get_float, 0.5, None), "subdiv_level": (Config.get_int, 2, None), "strength": (Config.get_float, 0.1, None), "min_vertices_for_subdiv": (Config.get_int, 10000, None)} # unpack result = self._unpack_params(displace_config, instructions) elif key == "cf_add_uv_mapping": uv_config = Config(params_conf.get_raw_dict(key)) # instruction about unpacking the data: key, corresponding Config method to extract the value, # it's default value and a postproc function instructions = {"projection": (Config.get_string, None, str.lower)} # unpack result = self._unpack_params(uv_config, instructions) else: result = params_conf.get_raw_value(key) params.update({key: result}) return params
def run(self): # bpy.context.scene.world["category_id"] = 0 bpy.context.scene.render.resolution_x = self.camera_info['width'] bpy.context.scene.render.resolution_y = self.camera_info['height'] # Collect camera and camera object cam_ob = bpy.context.scene.camera cam = cam_ob.data cam['loaded_intrinsics'] = np.array( [[self.camera_info['fx'], 0, self.camera_info['cx']], [0, self.camera_info['fy'], self.camera_info['cy']], [0, 0, 1]]) cam['loaded_resolution'] = self.camera_info['width'], self.camera_info[ 'height'] config = Config({}) camera_module = CameraInterface(config) camera_module._set_cam_intrinsics(cam, config) loaded_objects = [] # only load all/selected objects here, use other modules for setting poses # e.g. camera.CameraSampler / object.ObjectPoseSampler obj_ids = list(range(self.obj_df.shape[0])) # if sampling is enabled if self.sample_objects: loaded_ids = {} loaded_amount = 0 if self.obj_instances_limit != -1 and len( obj_ids ) * self.obj_instances_limit < self.num_of_objs_to_sample: raise RuntimeError( "{}'s {} split contains {} objects, {} object where requested to sample with " "an instances limit of {}. Raise the limit amount or decrease the requested " "amount of objects.".format(self.bop_dataset_path, self.split, len(obj_ids), self.num_of_objs_to_sample, self.obj_instances_limit)) while loaded_amount != self.num_of_objs_to_sample: obj_id = random.choice(obj_ids) if obj_id not in loaded_ids.keys(): loaded_ids.update({obj_id: 0}) # if there is no limit or if there is one, but it is not reached for this particular object if self.obj_instances_limit == -1 or loaded_ids[ obj_id] < self.obj_instances_limit: cur_obj = self._load_mesh(obj_id, scale=self.scale) loaded_ids[obj_id] += 1 loaded_amount += 1 loaded_objects.append(cur_obj) else: for obj_id in obj_ids: cur_obj = self._load_mesh(obj_id, scale=self.scale) loaded_objects.append(cur_obj) self._set_properties(loaded_objects)
def __init__(self, config): Module.__init__(self, config) # Clean up example scene or scene created by last run when debugging pipeline inside blender Initializer.cleanup() # setting up the GlobalStorage global_config = Config(self.config.get_raw_dict("global", {})) GlobalStorage.init_global(global_config) # call the init again to make sure all values from the global config where read correctly, too self._default_init()
def run(self): """ Constructs a ground plane. 1. Get configuration parameters. 2. Load shader. 3. Construct ground plane and it's material node tree. """ tiles = self.config.get_list("tiles") for tile in tiles: if tile: ground_config = Config(tile) self._load_shader(ground_config) self._construct_ground_plane(ground_config)
def add_item(self, parameters): """ Adds a new item based on the given parameters. :param parameters: A dict specifying the parameters. """ # Start with the default parameters data = deepcopy(self.default_item_parameters) # Overwrite default parameter values with specific parameters for this item data = Utility.merge_dicts(parameters, data) # Create config object config = Config(data) # Call function to add new item self.add_item_func(config)
def _apply_function(self, entity, key, result): """ Applies a custom function to the selected entity. :param entity: Entity to be modified via the application of the custom function. Type: bpy.types.Object. :param key: Name of the custom function. Type: string. :param result: Configuration parameters of the custom function. Type: dict. """ if key == "add_modifier": result = Config(result) name = result.get_string("name") # the name of the modifier if name.upper() == "SOLIDIFY": thickness = result.get_float("thickness") bpy.context.view_layer.objects.active = entity bpy.ops.object.modifier_add(type=name.upper()) bpy.context.object.modifiers["Solidify"].thickness = thickness else: raise Exception("Unknown modifier name: {}.".format(name)) elif key == "set_shading": result = Config(result) mode = result.get_string("cf_set_shaing") Loader.change_shading_mode([entity], mode) else: raise Exception("Unknown custom function name: {}.".format(key))